Getting dynamic response with AJAX

AJAX also known as Asynchronous JavaScript and XML, is a web technology to communicate with server and alter the content of the web page without reloading it. In this article, we will learn how to getting dynamic responses with AJAX?
Submitted by Abhishek Pathak, on October 07, 2017

AJAX also known as Asynchronous JavaScript and XML, is a web technology to communicate with server and alter the content of the web page without reloading it. The immense popularity of AJAX is due to the fact that modern web applications need to work like native applications. They shouldn't keep loading and waiting for new page every time.

See this article for more reference...

Though there are many libraries like jQuery, but I prefer to use Vanilla JavaScript. It is also easy to achieve what these libraries provide as a mechanism to send data between the server and client.

First of all, we need to create an XMLHttpRequest() object, which provides method to send and receive response from the server.

Code:

var xhr = new XMLHttpRequest();

After creating an object, we have to determine what this object will do upon response.

Code:

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

Now, what this code does is, it defines function for onreadystatechange event, and whenever there is any change it executes this code. The this.readyState property checks if the state is 4, which is the response has been received from server and also if this.status is equal to 200. There are various status numbers, I would suggest you to visit this link (http://www.restapitutorial.com/httpstatuscodes.html) to know more. Now if those conditions are met, then it means we got response from server and therefore, we alert that response using this.responseText.

Now, we need to send the data to server, which is done through open() and send() method.

Code:

xhr.open('GET', '/submit-data.php', true);
xhr.send();

The open() method has 3 arguments, the method by which content has to be sent - post or get, the server URL and whether the request should be sync or async, mostly it is true. The server URL is where data will be processed.

When the response will be received, it will execute the onreadystatechange function, and as I have already mentioned, it will alert the response, if any.

So, there you go. That's how you do dynamic stuff with AJAX?

Share your thoughts in the comments below.




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.