WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

AJAX - The onreadystatechange Event


The onreadystatechange event

When a demand to a server is sent, we need to play out certain activities based on the response.

The onreadystatechange occasion is set off each time the readyState changes.

The readyState property holds the status of the XMLHttpRequest.

Three essential properties of the XMLHttpRequest object:

Property Description
onreadystatechange Stores a capacity (or the name of a capacity) to be called naturally each time the readyState property changes
readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: ask for not introduced
1: server association established
2: ask for got
3: handling demand
4: ask for completed and reaction is ready
status 200: "OK"
404: Page not found

In the onreadystatechange occasion, we determine what will happen when the server reaction is prepared to be processed.

When readyState is 4 and status is 200, the reaction is ready:

Example

work loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = work() {
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    document.getElementById("demo").innerHTML = xhttp.responseText;
  }
};

Note: The onreadystatechange occasion is activated multiple times (0-4), once for each change in readyState.


Using a Callback Function

A callback work is a capacity gone as a parameter to another function.

If you have more than one AJAX undertaking on your site, you ought to make ONE standard capacity for making the XMLHttpRequest item, and call this for each AJAX task.

The work call ought to contain the URL and what to do on onreadystatechange (which is likely extraordinary for each call):

Example

work loadDoc(cFunc) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = work() {
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    cFunc(xhttp);
  }


Welookups is optimized for learning.Copy right 2018 kumar aditya singh .
All Right Reserved and you agree to have read and accepted our term and condition.
All Rights Reserved.

welookups.com