{"id":4146,"date":"2019-04-03T11:57:45","date_gmt":"2019-04-03T11:57:45","guid":{"rendered":"http:\/\/www.nikola-breznjak.com\/blog\/?p=4146"},"modified":"2019-04-03T11:57:45","modified_gmt":"2019-04-03T11:57:45","slug":"making-ajax-calls-using-jquery","status":"publish","type":"post","link":"https:\/\/nikola-breznjak.com\/blog\/javascript\/making-ajax-calls-using-jquery\/","title":{"rendered":"Making AJAX calls using jQuery"},"content":{"rendered":"<h2>TL;DR<\/h2>\n<p>In this post we&#8217;ll do everything (and a bit more ?) we did in the <a href=\"http:\/\/www.nikola-breznjak.com\/blog\/javascript\/making-ajax-calls-pure-javascript\/\">first post<\/a>, but with <a href=\"https:\/\/jquery.com\/\">jQuery<\/a>.<\/p>\n<h2>Why is jQuery better?<\/h2>\n<p>I prepared <a href=\"http:\/\/nikola-breznjak.com\/_testings\/ajax\/test3.html\">this demo page<\/a> so that you can test.<\/p>\n<p>You&#8217;ll remember from the last post that in order to make an AJAX call in pure JavaScript, you have to do something like this:<\/p>\n<pre><code>var xhr = new XMLHttpRequest();\nxhr.onreadystatechange = function() {\n    if (xhr.readyState === 4){\n        document.getElementById('result').innerHTML = xhr.responseText;\n    }\n};\nxhr.open('GET', 'http:\/\/nikola-breznjak.com\/_testings\/ajax\/test1.php?ime=Nikola');\nxhr.send();\n<\/code><\/pre>\n<p>Go ahead and run that code on the <a href=\"http:\/\/nikola-breznjak.com\/_testings\/ajax\/test3.html\">demo page<\/a> in the browser&#8217;s dev tools Console (consult the <a href=\"http:\/\/www.nikola-breznjak.com\/blog\/javascript\/making-ajax-calls-pure-javascript\/\">last post<\/a> if you&#8217;re stuck).<\/p>\n<p>Now, to do the very same thing with jQuery, all you have to do is this:<\/p>\n<p><code>$('#result').load('http:\/\/nikola-breznjak.com\/_testings\/ajax\/test1.php?ime=Nikola');<\/code><\/p>\n<p>Go ahead and try it in the Console. Change the <code>ime<\/code> parameter, and you&#8217;ll see that the text on the page will change to <code>Hello [name]<\/code>, where [name] will be the parameter you entered.<\/p>\n<blockquote><p>\n  \u26a0\ufe0f I won&#8217;t go into the basics of using jQuery, as it&#8217;s been here for a very long time, and there&#8217;s a vast amount of tutorials written about it. Start with the <a href=\"https:\/\/jquery.com\/\">official docs<\/a> if you want to learn more.\n<\/p><\/blockquote>\n<p>The important thing to note here is that <code>.load<\/code> must be chained to a so-called jQuery selection, as mentioned in the <a href=\"https:\/\/api.jquery.com\/load\/\">.load() documentation<\/a>. We loaded the data from the server and placed the returned text into the element with an id <code>result<\/code>.<\/p>\n<h2>Shorthand methods<\/h2>\n<p>By looking at the docs, you can see that there are more of these so-called <a href=\"https:\/\/api.jquery.com\/category\/ajax\/shorthand-methods\/\">shorthand methods<\/a> for making AJAX calls, all of which could be done with the most versatile <a href=\"https:\/\/api.jquery.com\/jQuery.ajax\/\">ajax<\/a> function.<\/p>\n<p>The example from before could be done using the <a href=\"https:\/\/api.jquery.com\/jQuery.get\/\">get<\/a> shorthand method:<\/p>\n<pre><code>    var link = 'http:\/\/nikola-breznjak.com\/_testings\/ajax\/test1.php';\n    var data = {ime:\"Nikola\"};\n    var callback = function(result) {\n        $('#result').html(result);\n    }\n    $.get(link, data, callback);\n<\/code><\/pre>\n<p>If you don&#8217;t want to pass any parameters, it gets even simpler:<\/p>\n<pre><code>    var link = 'http:\/\/nikola-breznjak.com\/_testings\/ajax\/test1.php';\n    var callback = function(result) {\n        $('#result').html(result);\n    }\n    $.get(link, callback);\n<\/code><\/pre>\n<h2>Rewriting the mini project<\/h2>\n<p>I prepared the same <a href=\"http:\/\/nikola-breznjak.com\/_testings\/ajax\/test4.html\">demo page<\/a> 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.<\/p>\n<pre><code>var link = 'http:\/\/nikola-breznjak.com\/_testings\/ajax\/test2.php';\n$.getJSON(link, function(result){\n    var oglasiHTML = '';\n    $.each(result, function(index, oglas){\n        var klasaCijene = '';\n        if (oglas.cijena &lt; 100){\n            klasaCijene = 'is-success';\n        }\n        else if (oglas.cijena &gt;= 100 &amp;&amp; oglas.cijena &lt; 300){\n            klasaCijene = 'is-info';\n        }\n        else if (oglas.cijena &gt;= 300){\n            klasaCijene = 'is-danger';\n        }\n\n        oglasiHTML += `\n            &lt;div class=\"columns\"&gt;\n                &lt;div class=\"column is-one-quarter\"&gt;\n                    &lt;span class=\"tag ${klasaCijene}\"&gt;${oglas.cijena}&lt;\/span&gt;\n                &lt;\/div&gt;\n                &lt;div class=\"column\"&gt;${oglas.tekst}&lt;\/div&gt;\n            &lt;\/div&gt;\n        `;\n    });\n\n    $('#oglasi').html(oglasiHTML);\n});\n<\/code><\/pre>\n<p>There are a few things that I&#8217;d like to point out here:<\/p>\n<ul>\n<li>I used the <a href=\"https:\/\/api.jquery.com\/jQuery.getJSON\/\">getJSON<\/a> function to call my API located on the URL that&#8217;s saved in the <code>link<\/code> variable. This is because I know that this API returns a JSON response (you can check by opening that link in the browser).<\/li>\n<li>I used the jQuery <a href=\"https:\/\/api.jquery.com\/each\/\">each<\/a> function to iterate over the <code>result<\/code>.<\/li>\n<li>I used the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Template_literals\">template literals<\/a> to construct the final <code>oglasiHTML<\/code> in a much cleaner way than we did that in the previous post with using concatenation.<\/li>\n<li>The core logic remained the same as in the first post, with the exception of not having to use the <code>for<\/code> loop and <code>indexes<\/code> to access each element of the array.<\/li>\n<\/ul>\n<h2>I want more examples<\/h2>\n<p><img decoding=\"async\" src=\"https:\/\/i.imgur.com\/jYSxnG9.jpg\" alt=\"\" \/><\/p>\n<p>Say you have <a href=\"http:\/\/nikola-breznjak.com\/_testings\/ajax\/test5-email.html\">this demo page<\/a>, and you need to make the newsletter signup form use AJAX instead of going to a new page when you click the <code>Subscribe<\/code> button. Right now the API (located at http:\/\/nikola-breznjak.com\/_testings\/ajax\/email.php) doesn&#8217;t actually process what you send to it, but try to send data with the request as well for practice.<\/p>\n<p>How would you do it? Where would you start?<\/p>\n<p>Well, here are a few search terms you could Google:<\/p>\n<ul>\n<li>`form submit jquery&#8217;<\/li>\n<li><code>post data<\/code><\/li>\n<\/ul>\n<p>Again, here&#8217;s my solution, but I encourage you to try it yourself first.<\/p>\n<pre><code>$('form').submit(function(ev){\n    ev.preventDefault();\n    var url = $(this).attr('action');\n    var formData = $(this).serialize();\n    $.post(url, formData, function(response){\n        $('#newsletter').html('Thank you for subscribing, please check your email.');\n    });\n});\n<\/code><\/pre>\n<p>There are a few things that I&#8217;d like to point out here:<\/p>\n<ul>\n<li>I was able to use the <code>form<\/code> selector without any id because it&#8217;s the only form on the page. If there were more forms on the page, I&#8217;d have to distinguish them by using an id (which is always a good practice, even if it&#8217;s just one form)<\/li>\n<li>I used jQuery&#8217;s <a href=\"https:\/\/api.jquery.com\/submit\/\">submit<\/a> function to set an event handler that will be executed when the form will be submitted (<code>Subscribe<\/code> button clicked, or ENTER pressed while in one of the fields)<\/li>\n<li>I used the <code>ev.preventDefault()<\/code> to prevent the form from &#8220;doing its thing&#8221; and loading the &#8217;email.php&#8217; page, as its default behavior<\/li>\n<li>I used <code>$(this).attr('action')<\/code> to extract the API URL from the form definition it the HTML (feel free to check it out in the element inspector)<\/li>\n<li>I used <code>$(this).serialize()<\/code> to encode a set of form elements as a string which I then passed to the jQuery <a href=\"https:\/\/api.jquery.com\/jQuery.post\/\">post<\/a> shorthand function. This function sends a request to the server using the POST method, which (as we learned in the previous post) is the preferred way of sending some sensitive data that needs to be handled on the server<\/li>\n<li>I used the <a href=\"https:\/\/api.jquery.com\/html\/\">html<\/a> function on a <code>div<\/code> with the id <code>newsletter<\/code> to set its new content<\/li>\n<\/ul>\n<h2>Can I have one more, please?<\/h2>\n<p>Sure, but promise you&#8217;ll do it yourself first!<\/p>\n<blockquote><p>\n  I do ?\n<\/p><\/blockquote>\n<p>OK then, let&#8217;s do this ?<\/p>\n<p>Here&#8217;s a new <a href=\"http:\/\/nikola-breznjak.com\/_testings\/ajax\/test6-slike.html\">demo page<\/a> that you&#8217;ll use for this example.<\/p>\n<blockquote><p>\n  \u26a0\ufe0f I&#8217;m using <a href=\"https:\/\/bulma.io\/\">Bulma<\/a> to make the site look pretty. As their website says:<br \/>\n  &#8216;Bulma is a free, open source CSS framework based on Flexbox and used by more than 150,000 developers.&#8217;<br \/>\n  I&#8217;ll just say it&#8217;s really great and easy to learn, so make sure you check it out.\n<\/p><\/blockquote>\n<p>In this challenge, you have to create a gif search application using the <a href=\"https:\/\/developers.giphy.com\/\">Giphy Search API<\/a>. As the docs state, you&#8217;ll need to get the API key by <a href=\"https:\/\/developers.giphy.com\/dashboard\/?create=true\">creating an app<\/a>. Once you do that, you&#8217;ll be able to search their API like, for example, this: <code>http:\/\/api.giphy.com\/v1\/gifs\/search?q=funny+cat&amp;api_key=dc6zaTOxFJmzC<\/code>. You can use this API key, but be sure to create your own if this one gets banned for too many requests ?\u200d<\/p>\n<p>Once you fetch the gifs (or still images if you so choose), show them in the div with a class <code>result<\/code> (yes, class, not id ?).<\/p>\n<p>Here&#8217;s the part where you roll up your sleeves, create it, feel proud of yourself ?, and then come here to check how I did it.<\/p>\n<pre><code>$('form').submit(function(ev){\n    ev.preventDefault();\n    var searchTerm = $('input').val();\n\n    var apiLink = \"http:\/\/api.giphy.com\/v1\/gifs\/search?api_key=dc6zaTOxFJmzC&amp;q=\" + searchTerm;\n\n    var output = '';\n    $.getJSON(apiLink, function(images){\n        $.each(images.data, function(i, im){\n            output += `&lt;img src=\"${im.images.downsized.url}\"\/&gt;`;\n        });\n\n        $('.result').html(output);\n    });\n});\n<\/code><\/pre>\n<p>The only new, and potentially tricky, part here is the traversal of the JSON object that you get back from the API, but with just a bit training, you&#8217;ll get good at it.<\/p>\n<p>If you open up <a href=\"http:\/\/api.giphy.com\/v1\/gifs\/search?api_key=dc6zaTOxFJmzC&amp;q=duck\">this URL<\/a> in your browser, you will see this<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/i.imgur.com\/Dbu9ge8.jpg\" alt=\"\" \/><\/p>\n<p>The returned JSON object consists of three properties:<\/p>\n<ul>\n<li><code>data<\/code><\/li>\n<li><code>pagination<\/code><\/li>\n<li><code>meta<\/code><\/li>\n<\/ul>\n<p>The <code>data<\/code> is an array of objects, and in one of its properties it has an array of <code>images<\/code>. In my example, I choose to display the <code>downsized<\/code> gif by accessing its <code>url<\/code> property.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/i.imgur.com\/ZEuMHuw.jpg\" alt=\"\" \/><\/p>\n<p>Here&#8217;s a short gif of this in action:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/i.imgur.com\/dZeGeZT.gif\" alt=\"\" \/><\/p>\n<h2>Conclusion<\/h2>\n<p>That&#8217;s all for this blog post. I hope it was useful and that you&#8217;ve seen how much easier it is to make AJAX requests with jQuery vs. plain JavaScript. I also hope you liked the demo exercises ?<br \/>\nIn the next blog post, we&#8217;ll see how to do this with the modern <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Fetch_API\">fetch API<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>TL;DR In this post we&#8217;ll do everything (and a bit more ?) we did in the first post, but with jQuery. Why is jQuery better? I prepared this&hellip;<\/p>\n","protected":false},"author":1,"featured_media":4147,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27],"tags":[],"class_list":["post-4146","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript"],"_links":{"self":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/4146","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/comments?post=4146"}],"version-history":[{"count":1,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/4146\/revisions"}],"predecessor-version":[{"id":4148,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/posts\/4146\/revisions\/4148"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/media\/4147"}],"wp:attachment":[{"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/media?parent=4146"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/categories?post=4146"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nikola-breznjak.com\/blog\/wp-json\/wp\/v2\/tags?post=4146"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}