The Ultimate Guide to JQuery AJAX



Hello dear readers! Welcome back to another edition of our tutorial on jQuery. In this tutorial guide, we are going to be discussing about the jQuery Ajax. Like i said in our last tutorial, Ajax is a full course on it's own which will be treated soon in this blog.

Ajax is an acronym that stands for Asynchronous JavaScript and XML. This technology helps us to load data from the web server without an actual browser page refresh.

JQuery is a nice tool that provides a rich set of Ajax methods for the development of next generation web applications.

Loading Simple Data

It is very easy to load any static or dynamic data using JQuery Ajax. JQuery provides a load( ) method to handle this task.

Syntax

The following below is the syntax for a load( ) method -

 [selector].load( URL ,  [data] ,  [callback] );

Parameter Details

Below is the description of all the parameters -

  • URL - This is the URL of the server side resource (SSR) to which the request was sent. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database.
  • data - This is an optional parameter that represents an object whose properties are serialized into few properly and encoded parameters to be passed to the request. If it is specified, the request is made using POST method. If omitted, the GET method is used.
  • callback - This is a callback function that is invoked after the response data must have been loaded to the matched set of elements. The first parameter that is passed to this function is the response text received from the server, and the second parameter is the status code.

Example

Below is a short example on how to implement this method -

<html>
     <head>
          <title>jQuery Example</title>
          <script  type = "text/javascript"   
               src = "https//ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js">               
          </script>  

          <script  type = "text/javascript">
               $( document ).ready( function( )  {
                    $( "#driver" ).click( function( event )  {
                         $( "#stage" ).load( '/jquery/result.html' );
                    } );
               } );
          </script>

     </head>

     <body>
          <span>Click on the button below to load /jquery/result.html file:</span>

          <div  id = "stage"  style = "background-color: yellow;">
               STAGE
          </div>
          
          <input  type = "button"  id = "driver"  value = "Load Data" />
     </body>
</html>

From the above example, the load( ) method initiates an Ajax request to the specified URL, that is the /jquery/result.html file. After this file must have loaded successfully, all of the contents will be occupied inside of the <div> tag with the ID name stage. Let us assume, that our /jquery/result.html file has just one HTML line -

<h1>THIS IS RESULT</h1>

Output

When you click on the given button below, then result.html files will be loaded -

jQuery Example Click on the button below to load /jquery/result.html file:
STAGE





Getting the JSON Data

There would be a situation when the server will return JSON string against your request. JQuery utility function getJSON() parses the returned JSON string and makes the resulting string to be available to the callback function as the first parameter to take further actions.

Syntax

Below is the syntax for a getJSON( ) method -

 [selector].getJSON( URL ,  [data] ,  [callback] );

Parameter Details

Below is the description of all the parameters -

  • data - This is an object whose properties serve as the name/value pairs that is used to construct the query string to be appended to the URL, or a pre formatted and encoded query string.
  • callback - This is a callback function that is invoked after the request completes. And also the data value resulting from digesting the response body as a JSON string is passed as first parameter to this callback, and the status as the second.

Example

Below is a short example on how to implement this method -

<html>
     <head>
          <title>jQuery Example</title>
          <script  type = "text/javascript"   
               src = "https//ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js">               
          </script>  

          <script  type = "text/javascript">
               $( document ).ready( function( )  {
                    $( "#driver" ).click( function( event )  {
                         
                         $.getJSON( '/jquery/result.json' ,   function( jd )    {
                              $( '#stage' ).html( '<p>  Name: '    +  jd.name  +  '</p>' );
                              $( '#stage' ).append( '<p>  Age: '  +  jd.age  +  ' </p>' );
                              $( '#stage' ).append( '<p>  Sex: '  +  jd.sex  +  '</p>' );
                         } );
                    
                    } );
               } );
          </script>

     </head>

     <body>
          <span>Click on the button below to load /jquery/result.json file:</span>

          <div  id = "stage"  style = "background-color: yellow;">
               STAGE
          </div>
          
          <input  type = "button"  id = "driver"  value = "Load Data" />
     </body>
</html>

Here, getJSON() method initiates an Ajax request to the specified URL, that is /jquery/result.json file. After this file must have loaded, all the content will be occupied inside of the <div> tag with the ID name stage. Now let us assume that our /jquery/result.json file has the json formatted content -

{

     "name" :  "Zara Ali",
     "age"     :  "67",
     "sex"      :  "female"

}

Output

When you click on the given button below, then result.html files will be loaded -

jQuery Example Click on the button below to load /jquery/result.json file:
STAGE





Pasaing Data to the Server

Many times you collect input from the user and you pass that input to the server which in turn processes the input further. JQuery Ajax has made it easy enough to pass the collected data to the web server making use of the data parameter of any available Ajax method.

Example

Below is a short example which demonstrates how to pass user input to a web server script, which would send the same result back and we would then print it -

<html>
     <head>
          <title>jQuery Example</title>
          <script  type = "text/javascript"   
               src = "https//ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js">               
          </script>  

          <script  type = "text/javascript">
               $( document ).ready( function( )  {
                    $( "#driver" ).click( function( event )  {
                         var  name =  $( "#name" ).val( );
                         $( "#stage" ).load( '/jquery/result.php' ,  { "name" : name } );
                    } );
               } );
          </script>

     </head>

     <body>
          <span>Enter your name and click on the show result button below :</span>
          <input  type = "input"  id = "name"  size = "50" /><br />

          <div  id = "stage"  style = "background-color: yellow;">
               STAGE
          </div>
          
          <input  type = "button"  id = "driver"  value = "Show Result" />
     </body>
</html>

The following below is the code written in result.php script -

<? php

     if( $_REQUEST[ "name" ] )  {
          $name =  $_REQUEST[ 'name' ] ;
          echo  "Welcome" . $name; 
     }

?>

Now you can enter any text in the given input box and then click on "Show Result" button to see what you have entered into the input box.

Output

When you click on the given button below, then result.html files will be loaded -

jQuery Example Enter your name and click on the show result button below :

STAGE





JQuery AJAX Methods

Now that you have seen the basic concepts of Ajax using jQuery. The following table below list down all the important jQuery Ajax methods that can be used based on your programming needs-

Sr.No.Methods & Description
1jQuery.ajax( options )
Load a remote page using an HTTP request.
2jQuery.ajaxSetup( options )
Setup global settings for AJAX requests.
3jQuery.get( url, [data], [callback], [type] )
Load a remote page using an HTTP GET request.
4jQuery.getJSON( url, [data], [callback] )
Load JSON data using an HTTP GET request.
5jQuery.getScript( url, [callback] )
Loads and executes a JavaScript file using an HTTP GET request.
6jQuery.post( url, [data], [callback], [type] )
Load a remote page using an HTTP POST request.
7load( url, [data], [callback] )
Load HTML from a remote file and inject it into the DOM.
8serialize( )
Serializes a set of input elements into a string of data.
9serializeArray( )
Serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with.

In our next tutorial post, the above listed methods will be discussed better with the use of examples.



JQuery AJAX Events
During the life cycle of an Ajax call progress, various jQuery methods can be called. So based on various events/stages, following methods are made available -

Sr.No.Methods & Description
1ajaxComplete( callback )
Attach a function to be executed whenever an AJAX request completes.
2ajaxStart( callback )
Attach a function to be executed whenever an AJAX request begins and there is none already active.
3ajaxError( callback )
Attach a function to be executed whenever an AJAX request fails.
4ajaxSend( callback )
Attach a function to be executed before an AJAX request is sent.
5ajaxStop( callback )
Attach a function to be executed whenever all AJAX requests have ended.
6ajaxSuccess( callback )
Attach a function to be executed whenever an AJAX request completes successfully.

Alright guys! We have come to the end of this tutorial post on JQuery AJAX. In our next tutorial, we will be using examples to demonstrate how the above listed methods can used.

Do feel free to ask your questions where necessary via the comment box below and i will attend to them as soon as possible.

Follow us on our various social media handles to stay updated with our latest tutorials. You can also subscribe to our newsletter to get our latest tutorials delivered directly to your emails.

Thanks for reading and bye for now.