jQuery AJAX

AJAX, standing for Asynchronous JavaScript and XML, is a set of web development techniques that allows web applications to communicate with a server asynchronously, without needing to refresh the whole page. jQuery, a fast and concise JavaScript library, simplifies the use of AJAX through its easy-to-use API.

Desired Outcomes: 

  • Understand what AJAX is?
  • Learn how to send AJAX requests, read responses, and listen for events.
  • Implement AJAX using jQuery.
  • Understand XML and JSON formats.

Traditionally, websites had to be refreshed each time in order to update their content. For example, web-based email platforms. The major disadvantage of refreshing pages was the loading speed. When a user refreshed the page, the server had to reconstruct the entire page, meaning it had to resend all the HTML, CSS, and JavaScript for rendering. By 2003, all major internet browsers had addressed this issue by implementing the XMLHttpRequest (XHR) object, which enabled browsers to communicate with the server without needing to refresh the pages.

The XMLHttpRequest object is part of a technology called AJAX (Asynchronous JavaScript and XML). With AJAX, data can be sent between the server and the browser via the XMLHttpRequest API without the need to reload the page. Thanks to the widespread use of these technologies, it quickly became possible to build internet applications like GoogleMaps, Gmail, and others.

Ajax requests are triggered using JavaScript code. The code sends a request to a URL and receives a response, after which a callback function can be triggered to process the response. Because the request is asynchronous, the rest of the code continues to execute while the request is being processed, which is why it's important to use a callback function.

Unfortunately, different browsers implement the Ajax API in different ways. This means that developers would have to consider all possible browsers when programming to ensure that Ajax works correctly in different browsers. Fortunately, jQuery's support for Ajax encompasses these differences.

jQuery provides a comprehensive $.ajax method as well as simpler methods like $.get(), $.getScript(), $.getJSON, $.post, and $.load.

Most jQuery applications don't use XML despite the name "Ajax"; instead, data is most often sent as HTML or JSON (JavaScript Object Notation), which you'll learn about in the following sections of this guide.

Generally, Ajax doesn't work across different domains. For example, a web page loaded on domain1.com can't send an Ajax request to domain2.com because it would violate the same-origin policy. As a solution to this problem, it's possible to use JSONP (JSON with Padding). JSONP uses <script> tags to load files containing JavaScript code and JSON from a different domain.

GET vs. POST

The two most common methods for sending requests to the server are GET and POST. It's important to understand the proper use of each.

The GET method should only be used when it's necessary to retrieve data from the server, not to change data on the server. For example, a search query on a page could be a GET request. GET requests can be saved in the browser's cache memory, which can cause unpredictable behaviors if you don't expect them. GET requests send all their data within the query string.

The POST method is most often used to send or change data on the server. For example, when a user registers for a certain service, user data is saved on the server. POST requests are usually not saved in the browser's cache memory, and while the query string may be part of the URL, the data is sent separately.

Ajax Data Types

Ajax typically requires instructions about the type of data it can expect to be returned from an Ajax request. In some cases, the data type is indicated by the method name, and in other cases, it may serve as part of the object.

Ajax data types include:

  • Text - for transmitting text (string) 
  • Html - for transmitting HTML code that will be used on the web 
  • Script - for adding scripts to the web page 
  • Json – for transmitting JSON-formatted data which may include strings, numbers, arrays, and objects 
  • Jsonp – for transmitting JSON data from a different domain 
  • Xml – for transmitting data using traditional XML

The JSON format is most commonly used because it offers the greatest flexibility. It's particularly useful for sending data and HTML code

Since Ajax calls are by default asynchronous, the server's response is not immediately available. Responses can only be processed using a callback function. For example, the following code will not work.

<script>
   var response;
   $.get( "mailer.aspx", function( r ) {
      response = r;
   });
   console.log( response ); // undefined
</script>

Instead of the above, it is necessary to pass a callback function within the request that will be executed after the request is successful.

$.get( "mailer.aspx", function( response ) {
   console.log( response ); // server response
});

When the server returns the request, it is possible to access the returned data if they exist.

JSON – JavaScript Object Notation

JSON (JavaScript Object Notation) is a textual format used for data exchange. It is used as an alternative to XML and is easy to understand. JSON uses JavaScript syntax but the format itself is text, like XML.

Characteristics of the JSON format are as follows:

  • The object is enclosed within curly { } brackets
  • It consists of key:value pairs (the key or name is written in double quotes) 
  • Pairs are separated by commas 
  • Values can be a string under double quotes, a number with a dot as a decimal separator, true/false, null, an array, or a JSON object
  • An array is enclosed in square [ ] brackets and consists of a sequence of values separated by commas

JSON is designed to easily convert into a string containing JSON and vice versa. Look at how the following JavaScript object is formatted in JSON format.

JavaScript:

// Javascript Object
<script>
   function Person() {
     this.FirstName = "John";
     this.LastName = "Doe";
     this.Phones = ["123456789", "0987654321"];
     this.Residence = {
       private: new Address("Street 1", 1),
       business: new Address("Street 2", 50)
     }
   }
 
   function Address(street, number) {
     this.Street = street;
     this.Number = number;
   }
</script>

JSON:

{
  "FirstName": "John",
  "LastName": "Doe",
  "Phones": [
    "123456789",
    "0987654321"
  ],
 
  "Address": {
    "Private": {
      "Street": "Street 1",
      "Number": 1
      },
    "Business": {
      "Street": "Street 2",
      "Number": 50
    }
  }
}

As seen in the above example, the JSON format is syntactically identical to the code for creating JavaScript objects. Thanks to these similarities, JavaScript scripts can use standard functions to convert JSON data into JavaScript objects.

Same-Origin Policy and JSONP

Ajax requests are usually limited to the same protocol (http or https), the same port, and the same domain that makes the request. Thanks to jQuery's Ajax methods, these restrictions do not apply to scripts that are loaded with them.

Another exception is requests that are sent to a JSONP service on a different domain. In the case of JSONP, the provider agrees to respond to the request with a script that can be loaded into the page using a <script> element. This script will contain the requested data wrapped in a callback function

Updated on:

Part of our complete: JQuery guide

Want exercises and real projects for this lesson? Get the full course.