How do you check whether an AJAX request has completed in Javascript?

Solution

The XMLHttpRequest object has readyState property and onreadystatechange which can be used to check whether the request has been processed.

  var xhttp;
  xhttp=new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 ) { 
      // Do something
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();

If you want to check the request has been processed successfully with 200OK status use can check status property of XMLHttpRequest object as shown below:

 var xhttp;
  xhttp=new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      //Do something
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();

Share this thread

Comments

Comments
comments powered by Disqus

Navigation

Social Media