getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2019
getButterfly

How to replace jQuery.ajax() with vanilla JavaScript in WordPress

In an effort to remove all jQuery dependency from one of my plugins, I decided to turn all jQuery.ajax() requests into vanilla JavaScript requests. Turns out it’s pretty simple.

Here’s the original request, before:

jQuery.ajax({
    type: 'post',
    url: ipAjaxVar.ajaxurl,
    data: 'action=imagepress-like&nonce=' + ipAjaxVar.nonce + '&imagepress_like=&post_id=' + pid,
    success: function (count) {
        if (count.indexOf('already') !== -1) {
            var lecount = count.replace('already', '');
            if (lecount === '0') {
                lecount = ipAjaxVar.likelabel;
            }
            like.removeClass('liked');
            like.html('<svg class="lnr lnr-heart"><use xlink:href="#lnr-heart"></use></svg> ' + lecount);
        } else {
            count = ipAjaxVar.unlikelabel;
            like.addClass('liked');
            like.html('<svg class="lnr lnr-heart"><use xlink:href="#lnr-heart"></use></svg> ' + count);
        }
    }
});

And here’s the vanilla JavaScript request, after:

var request = new XMLHttpRequest();

request.open('POST', ipAjaxVar.ajaxurl, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function () {
    if (this.status >= 200 && this.status < 400) {
        if (this.response.indexOf('already') !== -1) {
            if (this.response.replace('already', '') === '0') {
                likeLabel = ipAjaxVar.likelabel;
            }
            like.classList.remove('liked');
            like.innerHTML = '<svg class="lnr lnr-heart"><use xlink:href="#lnr-heart"></use></svg> ' + likeLabel;
        } else {
            likeLabel = ipAjaxVar.unlikelabel;
            like.classList.add('liked');
            like.innerHTML = '<svg class="lnr lnr-heart"><use xlink:href="#lnr-heart"></use></svg> ' + likeLabel;
        }
    } else {
        // Response error
    }
};
request.onerror = function() {
    // Connection error
};
request.send('action=imagepress-like&nonce=' + ipAjaxVar.nonce + '&imagepress_like=&post_id=' + pid);

Tested and working.

Read more about it here (POST requests using JavaScript) and here (using XMLHttpRequest).

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Added by Ciprian on Wednesday, April 25, 2018 in Blog, JavaScript

Do you want better SEO? More traffic? More conversions? More growth? We help companies exponentially grow their traffic and conversions, while outranking their competitors. With more than 10 years of experience, we’ve learned what is valuable to our clients.
SEO Dublin | SEO Malta

My Battle Tested Recommendations

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush

Disclaimer: These recommendations contain affiliate links.


Privacy Policy