How to make an AJAX call

An AJAX call is possibly one of the simplest and most useful things you’ll find when using JQuery and wanting to load some remote data (i.e. from an API) into your page without having to reload it. It’s something amazingly simple an easy, yet equally useful.

In this example we are gonna get some data from an API at Randomuser.me, and print the name and surname of the user we get from it.

This code is querying the API for a random user and putting its first name and last name into two different span elements with id firstname and lastname.

Let’s have a look at the different parts of the AJAX call:

  • method: This is the method you want to use for the request (e.g. GET, POST, PUT). This will be given to you by the API documentation you’re using. GET is normally used to receive data and POST and PUT for sending it. In this case we use GET as we’re receiving data for one user.
  • url: The URL you’re sending the request to, again check you API documentation.
  • datatype: This is the type of data we’re expecting from the query, in this case we know that we’re expecting an object in JSON notation, so we let the AJAX call know.
  • data: This is the data WE are sending to the server, in Object notation. The AJAX call will translate that into a string to append to the URL in case of GET or send key-value pairs for other methods like POST or PUT. If you prefer, you can write the string here. In this case, we’re asking the API to give us just 1 user, we don’t need more than that!
  • success: This is the function that will be called if the AJAX call succeeds. It receives the data as an argument of the function (in our example as r ). Check the documentation for more arguments.
  • error: This is the function that will be called if the AJAX call fails. Check the documentation for arguments it can receive.
  • complete: This function will be called when the AJAX is complete, independently that it’s been successful or not. In our example we’re using this function to hide the Loading… text. Note that this will be called after success/error functions. Check the documentation for arguments it can receive.

These are the basics for a simple AJAX, there’s a lot more to it of course! If you want to learn more about it check the JQuery Documentation for it: http://api.jquery.com/jquery.ajax/

I have put this call into a Javascript function that will be called when we click a button, if you want to have a look at the code check this Plunk:


Originally published at Sergibyte.