In this post we’ll do everything (and a bit more ?) we did in the first post, but with jQuery.

Why is jQuery better?

I prepared this demo page so that you can test.

You’ll remember from the last post that in order to make an AJAX call in pure JavaScript, you have to do something like this:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4){
        document.getElementById('result').innerHTML = xhr.responseText;
    }
};
xhr.open('GET', 'http://nikola-breznjak.com/_testings/ajax/test1.php?ime=Nikola');
xhr.send();

Go ahead and run that code on the demo page in the browser’s dev tools Console

Now, to do the very same thing with jQuery, all you have to do is this:

$('#result').load('http://nikola-breznjak.com/_testings/ajax/test1.php?ime=Nikola');

Go ahead and try it in the Console. Change the ime parameter, and you’ll see that the text on the page will change to Hello [name], where [name] will be the parameter you entered.

⚠️ I won’t go into the basics of using jQuery, as it’s been here for a very long time, and there’s a vast amount of tutorials written about it. Start with the official docs if you want to learn more.

The important thing to note here is that .load must be chained to a so-called jQuery selection, as mentioned in the .load() documentation. We loaded the data from the server and placed the returned text into the element with an id result.

Shorthand methods

By looking at the docs, you can see that there are more of these so-called shorthand methods for making AJAX calls, all of which could be done with the most versatile ajax function.

The example from before could be done using the get shorthand method:

    var link = 'http://nikola-breznjak.com/_testings/ajax/test1.php';
    var data = {ime:"Nikola"};
    var callback = function(result) {
        $('#result').html(result);
    }
    $.get(link, data, callback);

If you don’t want to pass any parameters, it gets even simpler:

    var link = 'http://nikola-breznjak.com/_testings/ajax/test1.php';
    var callback = function(result) {
        $('#result').html(result);
    }
    $.get(link, callback);

Rewriting the mini project

I prepared the same demo page as in the previous post, but with jQuery already included so you can test this by just pasting the code below in the Console. I encourage you first to try it yourself and then compare your solution with mine below.

var link = 'http://nikola-breznjak.com/_testings/ajax/test2.php';
$.getJSON(link, function(result){
    var oglasiHTML = '';
    $.each(result, function(index, oglas){
        var klasaCijene = '';
        if (oglas.cijena < 100){
            klasaCijene = 'is-success';
        }
        else if (oglas.cijena >= 100 && oglas.cijena < 300){
            klasaCijene = 'is-info';
        }
        else if (oglas.cijena >= 300){
            klasaCijene = 'is-danger';
        }

        oglasiHTML += `
            <div class="columns">
                <div class="column is-one-quarter">
                    <span class="tag ${klasaCijene}">${oglas.cijena}</span>
                </div>
                <div class="column">${oglas.tekst}</div>
            </div>
        `;
    });

    $('#oglasi').html(oglasiHTML);
});

There are a few things that I’d like to point out here:

  • I used the getJSON function to call my API located on the URL that’s saved in the link variable. This is because I know that this API returns a JSON response (you can check by opening that link in the browser).
  • I used the jQuery each function to iterate over the result.
  • I used the template literals to construct the final oglasiHTML in a much cleaner way than we did that in the previous post with using concatenation.
  • The core logic remained the same as in the first post, with the exception of not having to use the for loop and indexes to access each element of the array.

#jquery #ajax #javascript #api #developer

Making AJAX calls using jQuery
1.95 GEEK