[Coding Snippets #3]: Getting data from an endpoint, using jQuery's Ajax asynchronous calls

avatar

There is an infinite amount of ways to call a remote endpoint and get data. Some are easy, some are hard etc. jQuery's Ajax asynchronous calls are one of the easiest and reliable ways to do so.

jquery success-error.jpg

To make sure this works, you need to include jQuery BEFORE including the script below. In my example, I used jQuery 3.6.0, so this would be the script tag from jQuery's cdn.

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

And the code is as follows:

jQuery(document).ready(function () {

    $.ajax({
        url: "https://url.to.call/api",
        dataType: "text",
        success: function (data, status, jqXHR) {
            // Success! Execute what we want to do
        },
        error: function (jqXHR, textStatus, errorThrown) { 
            // Failure! Inform the user
         }
    });

});

Let's explain this line-by-line where needed!

Execute when it is safe to manipulate the page (or DOM, as Javascript/jQuery defines it)

jQuery(document).ready(function () {

Our code may or may not execute the code we want if we don't include this line. In oversimplified layman terms, the code inside this function will only execute after the page has finished loading.

Initiate an ajax call

 $.ajax({

We define that the code block inside this, is an ajax call. As an alternative, it may be written as jQuery.ajax({, but the result is the same.

url part

url: "https://url.to.call/api",

We define the remote endpoint in the url parameter. This could be a url on any domain, as long as we are allowed to access the resource because of CORS rules (Cross-origin resource sharing)*.

By default, we can use GET (query string) parameters on the url, like this:

url: "https://url.to.call/api?param=this&param2=" + that,

(param gets a hardcoded value of this, while param2 gets the value of variable that, that we have defined earlier in our script).

If you want to do a POST of data, you have to use jQuery.post() instead of jQuery.ajax(). I will explain jQuery.post() in a future "coding snippet" post.

* I could explain this to you, but you can lean more about CORS on MDN/Cross-Origin Resource Sharing (CORS) or Wikipedia/Cross-origin resource sharing.

What type of data we expect as a reply from the endpoint.

dataType by default is "GUESS WHAT I WANT!" (according, of course, to the data the remote endpoint sends). However, there are times we need to hardcode it, like this:

dataType: "text",

Available valid dataTypes: xml, html, script, json, jsonp, text

You can also use multiple types, seperated by space (like "text xml", will get a text reply, and try to parse it as an XML reply).

Was it a success....

success: function (data, status, jqXHR) {
    // Success! Execute what we want to do
},

Everything went as expected, so we can manipulate the received data and show it to the user (or do anything we want with it). We also get status (nothing we have to worry about, explained on the error section as textStatus) and jqXHR which contains some extra info (like responseText) but 9/10 times they are not needed. Be sure to look it up though if you want something more than the data from the endpoint reply.

Inside the function, we write our code to manipulate the reply, such as:

console.log(data)

or

$("#replydiv").append(data);

or whatever.

If data is of dataType json, we can use data.KEY (where key is an object name) to get a value we want.

... or a failure?

error: function (jqXHR, textStatus, errorThrown) { 
    // Failure! Inform the user or do whatever
}

Something went wrong, and we need to inform the user (or stop trying to manipulate the data, or whatever). textStatus in general (also used in success) can have the following possible statuses:

  1. abort
  2. error
  3. notmodified
  4. parsererror
  5. success
  6. timeout

and they can be used to notify the user about what happened in case of an error.

errorThrown holds a text representation of the error (like Page not found or anything else).

As is the case with success, inside the function we can write our code on how to handle the error.


Conclusion

And this concludes another coding snippet post, something that's all around the web, but is often overlooked (snobbed?) by developers because it seems like "last year" and "if you use framework X, it can be done in an easier way" (but without always taking in account what framework X may also bring that we may not need and how it may slow down a user's experience.


jQuery is an open source JavaScript framework, released under the M.I.T. license. It has brought many great things to the internet since released in 2006. Logo used (hopefully correctly) under the Trademark Policy of OpenJS Foundation.



0
0
0.000
3 comments
avatar

Congratulations @dimitrisp! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You distributed more than 24000 upvotes.
Your next target is to reach 25000 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out the last post from @hivebuzz:

Hive Power Up Month Challenge - Winners List
Hive Power Up Month - Feedback from Day 29
Hive Power Up Day - October 1st 2021 - Hive Power Delegation
0
0
0.000