Ajax Requests

AJAX Form Submission

When you need to submit a form without reloading the page, use AJAX. An example would be a form inside a modal popup. Instead of having your PHP form processing included on the same page, move it to a separate page and link to the page in your form element’s action attribute. Below are 2 versions of an AJAX request: jQuery and plain JS.

Vanilla JS AJAX Request

Fully documented plain JS POST request using AJAX:

// Vanilla JS AJAX code
(function() {
    var form = document.getElementById('feedback'); //replace feedback with form ID

    // Set up an event listener for the contact form.
    form.addEventListener("submit", function(event) {
        // Stop the browser from submitting the form.
        event.preventDefault();

        // Serialize the form data - convert to key:value pairs and urlencode
        // Must include serialize.js (included below or available from: https://vanillajstoolkit.com/helpers/serialize)
        var formData = serialize(form);

        //Select the element which will display the success/error messages - in this case, a custom div above the form
        var msgBox = document.querySelector('#msg-box');

        // Create AJAX request
        var ajax = new XMLHttpRequest();

        // Set the url for the request
        // Get path to form logger page from form 'action' attribute (be sure to set the action attr in form tag)
        var url = form.getAttribute("action");

        ajax.open('POST', url);

        // Set request headers
        ajax.setRequestHeader('X-Requested-With', 'XMLHttpRequest');  // Optional - allows server-side frameworks to identify Ajax requests
        ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // Specifies that we're sending a form

        // Specify what to do when the request is done
        ajax.onreadystatechange = function () {
            var DONE = 4; // readyState 4 means the request is done.
            var OK = 200; // status 200 is a successful return.
            if (ajax.readyState === DONE) {
                if (ajax.status === OK) {
                    // Put the response from the request in the msgBox container
                    msgBox.innerHTML = ajax.responseText;

                    // Clear the form (do this for each field on the form) 
                    document.getElementById('First_Name').value = '';
                    document.getElementById('Last_Name').value = '';
                    document.getElementById('Email_Address').value = '';
                    document.getElementById('Message').value = '';
                    // or hide the form entirely (or both)
                    //form.style.display = 'none';
                } else {
                    console.log('Error: ' + ajax.status); // Display the status error code in console.
                    msgBox.innerHTML('<p>Oops! An error occured and your message could not be sent.</p>');
                }
            }
        };
        ajax.send(formData);
    });
})();

// Serialize script (taken from: https://vanillajstoolkit.com/helpers/serialize)
var serialize = function (data) {
    var serialized = [];
    for (var i = 0; i < data.elements.length; i++) {
        var field = data.elements[i];
        if (!field.name || field.disabled || field.type === 'file' || field.type === 'reset' || field.type === 'submit' || field.type === 'button') continue;
        if (field.type === 'select-multiple') {
            for (var n = 0; n < field.options.length; n++) {
                if (!field.options[n].selected) continue;
                serialized.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.options[n].value));
            }
        }
        else if ((field.type !== 'checkbox' && field.type !== 'radio') || field.checked) {
            serialized.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value));
        }
    }
    return serialized.join('&');
};

jQuery AJAX

Original jQuery version of the same request

// jQuery AJAX code
$(function() {
    // Get the form.
    var form = $('#feedback');

    // Set up an event listener for the contact form.
    $(form).submit(function(event) {
        // Stop the browser from submitting the form.
        event.preventDefault();

        // Serialize the form data.
        var formData = $(form).serialize();

        var msgBox = $('#msg-box');

        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })

        .done(function(response) {
            // Set the message text.
            $(msgBox).html(response);

            // Clear the form.
            $('#First_Name').val('');
            $('#Last_Name').val('');
            $('#Email_Address').val('');
            $('#Message').val('');
        })
        .fail(function(data) {
            // Set the message text.
            if (data.responseText !== '') {
                $(msgBox).html(data.responseText);
            } else {
                $(msgBox).html('<p>Oops! An error occured and your message could not be sent.</p>');
            }
        });
    });
});