AJAX Post method example using javascript & jQuery

      

Usually AJAX requests are send through GET method. This is because there are few parameters that one send while sending a request through AJAX and also it is relatively easy to create and send a GET method request.
Following code is used generally to create a GET request through AJAX.

function getXMLHttpRequestObject()
{
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}
var http = new getXMLHttpRequestObject();

var url = "FetchSomeData.jsp";
var parameters = "name=krishna&age=16";
http.open("GET", url+"?"+parameters, true);
http.onreadystatechange = function() { //Handler function for call back on state change.
	if(http.readyState == 4) {
		alert(http.responseText);
	}
}
http.send(null);

Now the same code can be re-written in order to send the request by POST method. Check the following code:

var url = "FetchSomeData.jsp";
var parameters = "name=krishna&age=16";
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", parameters .length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Handler function for call back on state change.
	if(http.readyState == 4) {
		alert(http.responseText);
	}
}
http.send(parameters);

Now compare the two code snippets. The first change that you will see is in http.open() method.

//GET method
http.open("GET", url+"?"+parameters, true);

//POST method
http.open("POST", url, true);

In GET method, the parameters are appended with the URL and is passed in open() method, whereas in POST method the parameters are not passed with URL. The header is modified and the length of the parameter is set in it.

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters .length);
http.setRequestHeader("Connection", "close");

Hence in POST method, the parameters are send more as a form submission.

POST method using jQuery

Using jQuery one can easily send the request using POST method. See the following syntax.

$.post("GetData.jsp",
  { name: "John", time: "2pm" },
  function(data){
    alert("Data Loaded: " + data);
  }
);

Here the first argument to is the script name that one needs to call. Second argument is the parameters that one needs to pass in JSON format. And finally the handler function that will be called once the request has been completed.


Facebook  Twitter      Stumbleupon  Delicious
  

5 Comments on “AJAX Post method example using javascript & jQuery”

  • Nalin wrote on 2 April, 2009, 21:15

    AJAX Post method example using javascript & jQuery
    In the above POST method example on Ajax

    You are creating –>var parameters = “name=krishna&age=16″; and in the below method you are using params as the variable. So Is it right way to pass as below
    http.send(params); or should it be http.send(parameters);
    If required Please update the site.

  • casinos con bonos wrote on 3 April, 2009, 14:44

    i have seen the AJAX Post method example using JavaScript & j Query so its informative so i like it very much .so can i use the AJAX post method using the c# and .net .so thanks for the nice post.i appreciate to your efforts

  • Luigi Zambetti wrote on 15 June, 2009, 13:52

    And how can I get the passed values from the other pages (for example to “populate” some labels)?

    Luis

  • Viral Patel wrote on 15 June, 2009, 15:00

    Hi Luigi, Sorry, I did not understand your question. I think you want to get the values passed from Ajax in other pages?
    If this is the case then you can use normal server side script to get the data from request. For example in PHP $_REQUEST["somefield"] or in JSP request.getParameter("somefield");

  • idrish wrote on 17 December, 2009, 18:41

    hi, very well explained tuts..thanks…need a favour
    can you tell me what is wrong with this code

    $(document).ready(function(){

    $(‘#regist’).submit(function(e) {

    $.ajax({
    type: “POST”,
    url: “submit1.php”,
    data: $(‘form#regist’).serialize(),
    dataType: “json”,
    success: function(){
    $(“loading”).html(“here i am”);
    }
    });
    return false;
    e.preventDefault();

    });

    });

    this part does not seem to work….rest all is fine..i can update the DB if all conditions from submit1.php are met..also db does not get updated when conditions fail..(The page does not redirect to submit1.php, which is what i want..)
    success: function(){
    $(“loading”).html(“here i am”);
    }
    thanks in advance

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

Copyright © 2010 ViralPatel.net. All rights reserved.