Turn jQuery.ajax() request into XMLHttpRequest (vanilla JavaScript)

Here’s my take on it, although a bit late, but I am working on converting all jQuery.ajax() calls to vanilla JavaScript, so why not.

    // alpha JS request // no jQuery
    // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send#Example_POST
    // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
    var request = new XMLHttpRequest();

    request.open('POST', fpm_ajax.ajax_url, true);
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
    request.onload = function () {
        if (this.status >= 200 && this.status < 400) {
            // If successful
            console.log(this.response);
        } else {
            // If fail
            console.log(this.response);
        }
    };
    request.onerror = function() {
        // Connection error
    };
    request.send('action=work_hour_form_handler&work_hours_start=" + document.getElementById("work-hours--start').value + '&work_hours_end=' + document.getElementById('work-hours--end').value);
    //

Note that by using console.log(this) you can see the actual response and any thrown errors. Also note I haven’t included all your data, only the first two.

This code comes from a working solution from my WordPress plugin. I wrote about in more detail here: How to replace jQuery.ajax() with vanilla JavaScript in WordPress.

Enjoy!

Leave a Comment