What the f*ck is AJAX (for jQuery Programmers)? - A Complete Tutorial

AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.

·

5 min read

What the f*ck is AJAX (for jQuery Programmers)? - A Complete Tutorial

AJAX = Asynchronous JavaScript and XML. In short; AJAX is about loading data in the background and display it on the webpage, without reloading the whole page.

Examples of applications using AJAX: Gmail, Google Maps, Youtube, and Facebook tabs.

Now, to use AJAX, you must know jQuery. It's not that you cannot use AJAX without jQuery - in fact, you can. However, writing regular AJAX code can be a bit tricky, because different browsers have different syntax for AJAX implementation. This means that you will have to write extra code to test for different browsers. However, the jQuery team has taken care of this for us, so that we can write AJAX functionality with only one single line of code.

jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!

01 . Load ⚙️

The jQuery load() method is a simple, but powerful AJAX method.

The load() method loads data from a server and puts the returned data into the selected element.

The syntax for this is:

$(selector).load(URL,data,callback);

The required URL parameter specifies the URL you wish to load. The optional data parameter specifies a set of query string key/value pairs to send along with the request. The optional callback parameter is the name of a function to be executed after the load() method is completed.

Let's start by creating a simple HTML Page.

<!DOCTYPE html>
<html>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>

Our page currently looks like this:

When I press the button, nothing happens. Now, let's add jQuery using CDN.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

And now, let's get writing our jQuery.

$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("demo_test.txt");
  });
});

Let's understand this code:

$(document).ready(function(){

});

Whatever is in the function above will be loaded only when the document is ready, i.e., all elements are completely loaded. It's a good practice to write our jQuery inside the $ document.ready(function(){}) method.

$("button").click(function(){

  });

Whatever is inside the function above is executed only when the button element is clicked.

$("#div1").load("demo_test.txt");

This implies that the text from the file demo_test.txt will be loaded and will replace the text inside the element with id #div1. This is our demo_test.txt file:

<h2>jQuery and AJAX is FUN!</h2>
<p id="p1">This is some text in a paragraph.</p>

As you can see... AJAX replaces the entire HTML inside a particular tag in which it is targeted.

Now, let's load our webpage. This is our code:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("demo_test.txt");
  });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

And this is the output:

It looks the same... However, when I press the button, then the text changes.

What if I have a .txt file and I only want to load the content that has tag #p1 in the file and no other content must be loaded? Well... after the name of the file, I can specify the tag of the element to load.

$("#div1").load("demo_test.txt #p1");

This will only load the element with the tag p1 from demo_test.txt file.

The optional callback parameter specifies a callback function to run when the load() method is completed. The callback function can have different parameters:

  • responseTxt - contains the resulting content if the call succeeds

  • statusTxt - contains the status of the call

  • xhr - contains the XMLHttpRequest object

Let's display an alert box after the load() method completes. If the load() method has succeeded, it displays "External content loaded successfully!", and if it fails it displays an error message:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
      if(statusTxt == "success")
        alert("External content loaded successfully!");
      if(statusTxt == "error")
        alert("Error: " + xhr.status + ": " + xhr.statusText);
    });
  });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

Now, when we run this we get the following output:

When I click on this button, I get the following dialogue box:

If, however, I delete my .txt file, then the content should not load. In that case, I will get the following dialogue box:

02 . GET and POST 🏹

Two commonly used methods for a request-response between a client and server are: GET and POST.

  • GET - Requests data from a specified resource

  • POST - Submits data to be processed to a specified resource

GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.

POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.

02.01. GET

The $.get() method requests data from the server with an HTTP GET request.

$.get(URL,function(data,status){ });

The required URL parameter specifies the URL you wish to request. The optional callback parameter is the name of a function to be executed if the request succeeds. The following example uses the $.get() method to retrieve data from a file on the server:

Let's make a GET request to the following webpage: https://www.w3schools.com/jquery/demo_test.asp.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.get("demo_test.asp", function(data, status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>
</head>
<body>

<button>Send GET Request</button>

</body>
</html>

This is the output of the GET Request:

02.02. POST

The $.post() method requests data from the server using an HTTP POST request.

$.post(URL,data,function(data,status){ });

The required URL parameter specifies the URL you wish to request. The optional data parameter specifies some data to send along with the request. Data is usually a JavaScript object. The optional callback parameter is the name of a function to be executed if the request succeeds.

Let's send a POST Request to https://www.w3schools.com/jquery/demo_test_post.asp.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.post("demo_test_post.asp",
    {
      name: "Dhruv",
      city: "New Delhi"
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>
</head>
<body>

<button>Send POST Request</button>

</body>
</html>

This is the output of the POST Request:

This was all about the basic AJAX Methods in jQuery. There are other methods too, but they aren't frequently used. Hence, I won't be talking about them here.