JavaScript: What is AJAX?

JavaScript: What is AJAX?

October 6, 2019

Here’s a new article for you. Understanding XMLHttpRequest and Apply in AJAX.

If you ever find yourself confused about what ‘XMLHttpRequest‘ is referring to in JavaScript, take a look at the article.

Before reading about XMLHttpRequest we will know about AJAX.

Asynchronous JavaScript and XML

Ajax is a set of web development techniques using many web technologies on the client-side to create asynchronous web applications.

With Ajax, web applications can send and retrieve data from a server asynchronously without interfering with the display and behavior of the existing page.

AJAX stands for Asynchronous JavaScript and XML. It is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and JavaScript.

Famous web applications that make use of AJAX.

XMLHttpRequest Object in JavaScript

The XMLHttpRequest object can be used to request data from a web server. Let’s Understand by example.

AjaxExample.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>    
</head>
<body>
    <form action="#" method="get">
    <h1>Ajax Example</h1>      
        <div>
            <select name="" id="" onchange="getData(this.value)">
                <option value="State/UT">State/UT</option>
                <option value="Haryana">Haryana</option>
                <option value="Uttarakhand">Uttarakhand </option>
                <option value="Punjab">Punjab</option>
            </select>
        </div>
        <div>
            <select name="" id="cities" >
                <option value="">First Selct State</option>            
            </select>
        </div>
        <input type="submit" value="Send">        
    </form>    
</body>
</html>

Add CSS

form {
    position: relative;
    left: 30%;
    width: 500px;
    background: #f1f1f1;
    padding: 18px;
}

select {
    display: block;
    width: 100%;
    margin-bottom: 10px;
}

input[type="text"] {
    display: block;
    width: 100%;
    margin-bottom: 10px;
}

Add JavaScript AJAX Code

function getData(data){

           var xhttp = new XMLHttpRequest();

           xhttp.onreadystatechange = function()
           {
                   if (this.readyState == 4 && this.status == 200)
                   {
                      document.getElementById("cities").innerHTML = xhttp.responseText;
                   }
           };

           xhttp.open("GET", "AjaxExampleRequestPage.php?state="+data, true);
           xhttp.send();
           }

Explanation:

The onreadystatechange property defines a function to be executed when the readyState changes. The readyState property holds the status of the XMLHttpRequest. The status property and the statusText property holds the status of the XMLHttpRequest object.

Property Description
onreadystatechange Defines a function to be called when the readyState property changes
readyState Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: “OK”
403: “Forbidden”
404: “Page not found”
For a complete list go to the
Http Messages Reference
statusText Returns the status-text (e.g. “OK” or “Not Found”)

AjaxExampleRequestPage.php

<?php

$state= $_GET['state'];

$city1=[
        'Faridabad',
        'Gurugram',
        'Panipat',
        'Ambala',
        'Yamunanagar',	
        'Rohtak',
        'Hisar'	,
        'Karnal',
        'Sonipat',	
        'Panchkula'	,
        'Bhiwani',
        'Sirsa'	,
        'Bahadurgarh',
        'Jind',
        'Thanesar'	,
        'Kaithal',
        'Rewari',
        'Palwal',	
        'Pundri',	
        'Kosli'	,
      ];
$city2=[
    'Dehradun',
    'Haridwar',
    'Roorkee',
    'Haldwani-cum-Kathgodam',
    'Rudrapur',	
    'Kashipur',
    'Rishikesh'	    
  ];
$city3=[
    'Ludhiana'	,
'Amritsar'	,
'Jalandhar'	,
'Patiala'	,
'Bathinda',
'Hoshiarpur',
'Mohali'	,
'Batala',
'Pathankot',	
'Moga'	,
'Malerkotla',	
'Khanna'	,
'Phagwara'	,
'Muktasar',
'Firozpur',	
'Kapurthala',
'Sunam',];


if($state == 'Haryana'){
    foreach($city1 as $c1){
        echo '<option value="' . $c1 .'">'.$c1 .'</option>';
    }
}
else if($state == 'Uttarakhand'){
    foreach($city2 as $c2){
        echo '<option value="' . $c2 .'">'.$c2 .'</option>';
    }
}
else if($state == 'Punjab'){
    foreach($city3 as $c3){
        echo '<option value="' . $c3 .'">'.$c3 .'</option>';
    }
}
else{
    echo "<option value="' . 'Please Select State First' .'">'."Please Select State First".'</option>";
}


?>



Query example

jQuery still uses XMLHttpRequest behind the scenes, the following is a client-side implementation of the same example as above using the ‘ajax()’ method.

$.ajax({
  type: 'GET',
  url: 'send-ajax-data.php',
  dataType: "JSON", // data type expected from server
  success: function (data) {
    console.log(data);
  },
  error: function(error) {
    console.log('Error: ' + error);
  }
});

Advantages of AJAX

  • Reduce the traffic travels between the client and the server.
  • Response time is faster so it increases performance and speed.
  • You can use JSON (JavaScript Object Notation) which is an alternative to XML. JSON is a key-value pair and works like an array.

AJAX & HTTP Specifics

HTTP Methods

> GET  - Requests data from a resource
> POST - Submits data to be processed to a specified resource
> DELETE - Deletes the resource

> GET  - pulls
> POST - creates
> DELETE - removes

HTTP Status Codes

100-level - indicates that the request was received and understood
200-level - indicates the action requested by the client was received and understood, accepted and processed sucessfully
300-level - indicates that client must take addtional action to complete the, often used for redirection
400-level - The error seems to have been caused by client
500-level - The server failed to fulfill a valid request

100-level - hold on
200-level - here you go
300-level - go away
400-level - you messed up
500-level - server's messed up