JavaScript: gestire l'invio di un form in AJAX

Short link

In JavaScript è semplice gestire l'invio di un form in AJAX.

La soluzione è la seguente:


'use strict';

const request = (url, queryString, callback) => {
    let httpRequest = new XMLHttpRequest();

    httpRequest.open('POST', url);
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    httpRequest.send(queryString);
    httpRequest.onreadystatechange = () => {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                let response = JSON.parse(httpRequest.responseText);
                callback(response);
            }
        }
    };
};

const serialize = form => {
    let qs = [];
    Array.prototype.forEach.call(form.elements, element => {
        if(element.type !== 'submit') {
            let part = element.name + '=' + encodeURIComponent(element.value);
            qs.push(part);
        }
    });
    return qs.join('&');
};

document.addEventListener('DOMContentLoaded', () => {
    let form = document.querySelector('#form');
    form.addEventListener('submit', e => {
        e.preventDefault();
        request('/ajax/post', serialize(form), resp => {
            document.querySelector('#output').innerHTML = resp.message;
        });
    });
});