XMLHttpRequest in JavaScript
We can make HTTP request using JavaScript XMLHttpRequest
object.The XMLHttpRequest object are used to exchange data between server and web page.We can retrieve data from a URL using XMLHttpRequest
without refresh whole page.
Syntax
var httpReq=new XMLHttpRequest() httpReq.open(type,url,async); httpReq.send(); httpReq.onreadystatechange=function(){ if(xmlhttp.readyState === 4 && xmlhttp.status === 200){ console.log(httpReq.responseText); } }
Method/Property | Description |
---|---|
type | GET or POST Method |
async | To indicate the request is asynchronous or not. If we use true, we receive a callback when the request is finished. |
open() | Initializes the XMLHttpRequest. |
send() | Sends the XMLHttpRequest. |
onreadystatechange | is an EventHandler. Which is executed every time when the readyState changes. |
readyState |
State of our request.
|
status |
|
The following example shows, how to retrieve data from URl using XMLHttpRequest object.
Example
var httpReq=new XMLHttpRequest(); httpReq.open("GET","test/get_data.php",true); httpReq.send(); httpReq.onreadystatechange=function(){ if(httpReq.readyState === 4 && httpReq.status === 200){ document.querySelector("#output").innerHTML=httpReq.responseText; } }Try it Yourself
get_data.php
<?php echo "This message is response for XMLHttpRequest from server."; ?>