We use open() and send() method of XMLHTTPRequest to exchane data with the server.
Open method accepts 3 arguments method, url and a async. Method determines the type of request you wanna make, either POST or GET. URL gives the path to the file which will provide the data and async remains true for asynchronous and false for synchronous.
In programming, asynchronous events are those occurring independently of the main program flow. Asynchronous actions are actions executed in a non-blocking scheme, allowing the main program flow to continue processing. We set the AJAX request asynchronous so that browser can do any other work till the response from server is received.
So, here is how we send a GET request to the server :-
http.open("GET","demo.php?t=" + Math.random(),true); http.send();
In case there is nothing (no parameters) to send to the file, we use a random parameter , generated through jScript function Math.random() so that we don't receive any catched result.
We can similarly send any data if we wish using GET request by appending the URL with the parameters as we do in simple GET requests used in forms. Here is an example :-
However for sending data through POST variable , we need to add an HTTP header with setRequestHeader() and then we specify the data in the send method.
http.open("POST","demo.php",true); http.setRequestHeader("Content-type","application/x-www-form-urlencoded"); http.send("name1=Henry&name2=Ford");
setRequestHeader accepts two arguments, header and value. While header specifies the header name , value specifies the header value.
Once we are done with sending the XMLHTTPRequest object , lets see how to use the response from the server.