CodesJava

Easy learning with example program codes

ajax http response example


As we discussed in previous tutorial that XMLHttpRequest object is used for communication between client and server.

The onreadystatechange, readyState, status and statusText properties are used in ajax http response.

Ajax object properties

PropertyDescription
onreadystatechangeIt defines a function to be called when the readyState property changes
readyStateIt holds the status of the XMLHttpRequest.

XMLHttpRequest Status:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

responseTextIt returns the response data as a string.
responseXMLIt returns the response data as XML data.
statusIt returns the status-number of a request. For example:
200: “OK”
403: “Forbidden”
404: “Not Found”
statusTextIt returns the status-text (For example “OK” or “Not Found”).

 

Example

<!DOCTYPE html>
<html>
<body>
 
<div id="test">
<h2> Ajax http response</h2>
<button type="button" onclick="loadDocument()">Change Content</button>
</div>
 
<script>
function loadDocument() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("test").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "test.txt", true);
  xhttp.send();
}
</script>
 
</body>
</html>

 

Please follow and like us:
Posted in Ajax   


Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki