Saturday, May 9, 2020

The Ultimate Guide to JQuery AJAX



Hello guys! Welcome to a new section of my tutorial on jQuery. In this tutorial, am going to be discussing about the jQuery Ajax. Like i said in my last tutorial post, Ajax is a full course on its own which will be treated soon in this blog.

Ajax is an acronym for Asynchronous JavaScript and XML and this technology helps us in loading data from the server without an actual browser page refresh.

JQuery is a very great tool which provides a rich set of Ajax methods to develop next generation web applications.

Loading Simple Data

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

Syntax

Below is the syntax for a load( ) method -

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

Parameter Details

Below is the description of all the parameters -

  • URL - The URL of the server side resource (SSR) to which the request was sent to. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database.
  • data - This optional parameter represents an object whose properties are serialized into few properly and encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used.
  • callback - A callback function invoked after the response data must have been loaded into 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>

So from the above example, the load( ) method initiates an Ajax request to the specified URL I.e /jquery/result.html file. After loading this file, all the content will be occupied inside 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 - An object whose properties serve as the name/value pairs that's used to construct the query string to be appended to the URL, or a pre formatted and encoded query string.   
  • callback - A callback function invoked after the request completes. And also the data value that is 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>

So from the above example, the getJSON( ) method initiates an Ajax request to the specified URL I.e /jquery/result.json file. After loading this file, all the content will be occupied inside the <div> tag with the ID name stage. 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 this input further. JQuery Ajax made it easy enough to to pass the collected data to the server using 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>

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 my new tutorial, the above listed methods will be discussed better with the use of examples. 



JQuery AJAX Events
You can call various JQuery methods during the life cycle of AJAX call progress. So based on various events/stages, the 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 on JQuery AJAX. In my next tutorial, i will be making use of examples to demonstrate how the above listed methods can used.

Feel free to ask your questions where necessary and i will attend to them as soon as possible. Follow us on our various social media handles ( facebook,  twitter, linkedin, instagram, Pinterest ) and also subscribe to our newsletter to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.
Share:

0 comments:

Post a Comment