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

Been looking for some help changing a jQuery.ajax() request into vanilla XMLHttpRequest for WordPress, but not really finding what I want. Can anyone help me reformat the below into vanilla JavaScript XMLHttpRequest?

$.ajax({
    data: {
        'action': 'work_hour_form_handler',
        'work_hours_start': document.getElementById('work-hours--start').value,
        'work_hours_end': document.getElementById('work-hours--end').value,
        'break-hours_start': document.getElementById('break-hours--start').value,
        'break-hours_duration': document.getElementById('break-hours--duration').value,
        'working_days': document.getElementById('working-days').value
    },
    headers: {},
    method: 'post',
    url: fpm_ajax.ajax_url
}).done(function (data) {
    // If successful
    console.log(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
    // If fail
    console.log(textStatus + ': ' + errorThrown);
});

1 Answer
1

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