Categories
JavaScript

Using AJAX

Ajax (Asynchronous JavaScript and XML) allows you to send and retrieve data from a server asynchronously and process the data using JavaScript. In this tutorial, we create, configure, and execute AJAX requests.

XMLHttpRequest

In this tutorial, we use XMLHttpRequest object to set up and make AJAX requests:

  1. Create an XMLHttpRequest object:
let xhr = new XMLHttpRequest();

2. Call the XMLHttpRequest.open() method to initialized the request:

//Syntax
xhr.open(method, url, async, user, password)
  • method: HTTP request method (POST, GET, etc.)
  • url: the URL to send the request to
  • async: (optional) default value is true (asynchronous communication).
  • user: (optional) if the url is password protected, provide the username for the authentication purpose.
  • password: (optional) provide the password to authenticate the user.
 let xhr = new XMLHttpRequest();
 xhr.open("GET","https://brainbell.com/ajax.php?color=red");

3. Call the XMLHttpRequest.send() method to send the request to the server.

// Using GET metho
let xhr = new XMLHttpRequest();
xhr.open("GET","https://brainbell.com/ajax.php?color=red");
xhr.send()

The send() method accepts an optional parameter to specify the form data if the request method is POST. You also need to specify the request header and encode the data (if it contains special characters, such as space, ampersand, etc.) with encodeURIComponent method when POST method is used:

// Using POST method
let xhr = new XMLHttpRequest();
xhr.open("POST","https://brainbell.com/ajax.php");
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send("color="+encodeURIComponent("red & blue")+"&id=2")

4. To receive response from the server you need to create a callback function to handle the response. The XMLHttpRequest.onreadystatechange property called when request change the state:

xhr.onreadystatechange = cbFunction;
function cbFunction() {
 if (xhr.readyState === 4) {

 }
}

The readystatechange event is triggered several times through the request process, giving you updates about how things are going, the readyState method returns the current state of the xhr:

  • 0 – Initialized
  • 1 – open() method called
  • 2 – send() method called
  • 3 – receiving response
  • 4 – completed

5. The XMLHttpRequest.status property returns the HTTP status code of the server response, for example, a value of 200 indicates success, 500 indicates server error, 404 indicates page not found on the server.

xhr.onreadystatechange = cbFunction;
function cbFunction() {
 if (xhr.readyState === 4 && xhr.status === 200) {
  
 }
}

6. After checking the state of the request and the HTTP status code of the response, you get the data that the server sent using the one of the following properties:

  • XMLHttpRequest.responseText
    returns the server response as plain text
  • XMLHttpRequest.responseXML
    returns the response as an XMLDocument object

The following example uses the responseText property to display the data that the server sent:

let xhr = new XMLHttpRequest();
xhr.open("GET","https://brainbell.com/ajax.php?color=red");
xhr.send()
xhr.onreadystatechange = cbFunction;
function cbFunction() {
 if (xhr.readyState === 4 && xhr.status === 200) {
  alert( xhr.responseText );
 }
}

The following example uses the responseXML property to display the following data that the server sent:

<?xml version="1.0" ?>
<name>BrainBell.com</name>

XMLHttpRequest.responseXML example:

let xhr = new XMLHttpRequest();
xhr.open("GET","https://brainbell.com/ajax.php?data=xml");
xhr.send()
xhr.onreadystatechange = cbFunction;
function cbFunction() {
 if (xhr.readyState === 4 && xhr.status === 200) {
  let xml = xhr.responseXML;
  let name = xml.querySelector("name");
  alert (name.firstChild.data);
 }
}

The above example will display BrainBell.com alert box.

Note: You can use querySelector(), querySelectorAll(), getElementsByTagName() to retrieve data from responseXML.

AJAX – Sending Form Data Using a FormData Object

When you create a FormData object, you can pass an HTMLFormElement object, and the value of all of the fields in the form will be gathered up automatically including the input file fields.

  1. Retrieve HTMLFormElement object
let form = document.getElementById("formId");

//or
let form = document.forms.formId;

//or, first form in the document
let form = document.forms[0];

2. Use the submit event when the user clicks a submit button or presses enter button on the keyboard:

form.addEventListener('submit', cbFormSubmit);

3. The preventDefault() prevents the default action of submitting the form. Create a new FormData object and pass form object, and the value of all of the fields in the form will be gathered up automatically including the file fields.

function cbFormSubmit(e) {
 form.preventDefault();
 let formdata = new FormData(form);
}

4. Finally, use the XMLHttpRequest.send(FormData) to send the form data to the server. Following is the complete ajax code for sending the form data to the server:

window.onload = function() { 
 let form = document.getElementById("formId");
 form.addEventListener('submit', function (event) {
  event.preventDefault();
  let formdata = new FormData(form);
  let xhr = new XMLHttpRequest();
  xhr.open("POST","ajax.php");
  xhr.send(formdata)
  xhr.onreadystatechange = function (e) {
   if (xhr.readyState === 4 && xhr.status === 200) {
    //let xml = xhr.responseXML;
    let txt = xhr.responseText;
    alert (txt)
   }
  }
 });
}

Note: We use window.onload event handler to ensure that our code isn’t run until the page is loaded and the all HTML elements are completely set up.

AJAX – Handling JSON Response

JSON.parse ( xhr.responseText );

JSON – JavaScript Object Notation

Anything that can be stored in XML can also be stored in JSON. Both are text-based representations of data, but while XML requires opening and closing tags, JSON just uses colons, commas, and curly braces.

XML:

<?xml version="1.0" ?>
<name>BrainBell.com</name>

JSON:

{"name":"BrainBell.com"}

JSON.parse()

The JSON.parse() method parses a string text as JSON, for example, if your server send data in json format, you can use this method to convert it to JSON object:

if (xhr.readyState === 4 && xhr.status === 200) {
 //let xml = xhr.responseXML;
 let json = JSON.parse ( xhr.responseText );
}

Example: AJAX Code and Form:

<html>
 <head>
<script>
window.onload = function() { 
 let form = document.getElementById("formId");
 form.addEventListener('submit', function (event) {
  event.preventDefault();
  let formdata = new FormData(form);
  let xhr = new XMLHttpRequest();
  xhr.open("POST","ajax.php");
  xhr.send(formdata)
  xhr.onreadystatechange = function (e) {
   if (xhr.readyState === 4 && xhr.status === 200) {
    // Process the response
    //let xml = xhr.responseXML;
    //let txt = xhr.responseText;
    //let json = JSON.parse (xhr.responseText);
    alert(xhr.responseText);
   }
  }
 });
}
</script>
 </head>
 <body>
<form id="formId">
 <label for="name">Username:</label><br>
 <input type="text" name="name" value=""><br>

 <label for="email">Email:</label><br>
 <input type="text" name="email" value=""><br>

 <label for="uploads">Upload Images:</label><br>
 <input type="file" name="upload"><br>
 
 <input type="submit" name="submit" value="Save">
</form>
 </body>
</html>