DEV Community

Discussion on: Hating jQuery will not make you cool

 
tobiassn profile image
Tobias SN

Here's an AJAX call in jQuery:

$.ajax({
    url: "/faq/ajax",
    datatype: 'json',
    type: "POST",
    data: {search:'banana'},
    success: (r) => {
        console.log(r['name']);
    }
});

And it's Vanilla JS equivalent:

var r = new XMLHttpRequest();
r.open("POST", "/faq/ajax", true);
r.onreadystatechange = () => {
    if (r.readyState != 4 || r.status != 200) {
        return;
    }
    var a = JSON.parse(r.responseText);
    console.log(a.name);
};
r.send("search=banana");

To me, the jQuery version is clearly simpler and easier to read, with much less boilerplate.

And remember that the Fetch API still isn't fully supported on some browsers, so some people will still prefer AJAX.

Thread Thread
 
nitishk72 profile image
Nitish Kumar Singh • Edited

Yes, Vanilla JavaScript code is pretty ugly and I completely agree with that but using library just because your code doesn't look pretty is not a good idea at all. It will cost you a lot ( 30 kb).

Remember You can make the code more readable just by breaking it into function.

function ajaxRequest(url, params, callback){
    var request = new XMLHttpRequest();
    request.onreadystatechange = function()
    {
        if (request.readyState == 4 && request.status == 200)
        {
            callback(request.responseText); 
        }
    }; 
    request.open('GET', url);
    request.send();

}
    ajaxRequest('https://www.domain.com', null,function(response){
       console.log(response);
    }); 


Thread Thread
 
tobiassn profile image
Tobias SN

That was just an example. There could be a bunch of these cases in the code, and besides, 30 kB isn’t all that much anyway.