Using POST method in XMLHTTPRequest(Ajax)
December 12th, 20072 Comments
Requirements
Create a XMLHTTPRequest Object that uses the POST method.
Using GET method
Now we open a connection using the GET method.
var params = "lorem=ipsum&name=binny";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {
//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);}}
http.send(null);
I really hope that this much is clear for you
POST method
We are going to make some modifications so POST method will be used when sending the request…
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);}}
http.send(params);
The first change(and the most obvious one) is that I changed the first argument of the open function from GET to POST. Also notice the difference in the second argument – in the GET method, we send the parameters along with the url separated by a ‘?’ character…
But in the POST method we will use just the url as the second argument. We will send the parameters later.
Some http headers must be set along with any POST request. So we set them in these lines…
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
With the above lines we are basically saying that the data send is in the format of a form submission. We also give the length of the parameters we are sending.
//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);}}
We set a handler for the ‘ready state’ change event. This is the same handler we used for the GET method. You can use the http.responseText here – insert into a div using innerHTML(AHAH), eval it(JSON) or anything else.
http.send(params);
Wednesday, December 12th, 2007 at 11:26 am
how read this post(params) on server side.
Wednesday, December 12th, 2007 at 11:26 am
Hi-
You can read those parameters using $_GET method on server side.