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.



23 Comments

  • Nalin 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 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 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 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 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

  • plr store 25 October, 2010, 20:08

    sweet code,

    idrish, the page wont redirect, to submit1.php, it will fetch that page’s content and update it within a div or any tag that you specify.

  • scripty 22 November, 2010, 0:36

    In your jquery post method,

    For the first argument, are you sending data to the jsp page? or are you getting data from the jsp page, may you please tell me, and why do we need json, can we do it without json?

  • fati 23 August, 2011, 19:04

    Hi Viral, can you help enlighten me? how can I make your code work on file uploads such uploading image. If I pass the $_FILES[''image] to the parameter, then will it be able to send the file as well?

  • kedar 5 April, 2012, 9:15

    Hi viral, it was a very nice post…but i want to know after post the data using $.post or req.open(“GET” or “POST”) …and doing some process in the “test.php” how can i get the values in the original php program…if i have do perform “onchange” event of dropdown. Please let me asap…my work held up

  • sumit kumar jain pithani 3 August, 2012, 10:45

    sir,
    a nice code in post method using ajax but i have problem in mozile firefox it haven’t coming the alert box in mozile firefox using same code in post method.
    why it happen can u explain sir

  • Vimal 20 November, 2012, 15:10

    Hi Viral,
    Very Good post.
    I wanted to post very long characters in parameters like more than 3000 chars.
    Can we do that?

  • Selva C 26 November, 2012, 2:49

    Hi Viral,
    Am new to JQuery & Ajax. Could you please help me on the below.
    Am using Struts + JQuery + Ajax.
    1. Have login.jsp page which has user id & pwd. Values passed through $.post().
    2. Action class is getting the login values, validating & returning the success message.
    3. Am able to put the result in alert, but not able to navigate to that page.
    4. The intended (admin.jsp) page coding is coming in the alert.

    Please help me to render the results to the admin.jsp page.

    • Kulbhushan 19 December, 2013, 11:01

      Hi Selva did you find something on your problem, it yes the can u plz mail me @ kchaskar@aumtech.com

  • jasmin 24 April, 2013, 12:41

    Can i get this font-family : monospace;
    for windows ??

  • Mary 25 June, 2013, 20:30

    Hi, I have a POST method in java:

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
             ........
            conn.setRequestProperty(USERNAME, "user"));
            .........
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write("a string");
            wr.flush();
            conn.connect();
    

    and I would translate it in javascript. The problem is that I don’t know how translate the OutputStreamWriter object with jquery. Is there a solution?

  • rishi tripathi 13 July, 2013, 11:03

    GET and POST basically allow information to be sent back to the webserver from a browser (or other HTTP client for that matter).

  • keffy 23 August, 2013, 14:37

    i have send request to servlet by POST method using java Script . Problem is that request is going to servlet but i did not get any parameters. in servlet when i have written String name = request.getParameter(“name1″). then in servlet i got String name = NULL. please help me

  • Aditi 25 November, 2013, 17:39

    I am sending post request through ajax as follow:
    $.ajax({
    type : ‘POST’,
    url : “Activity_Resource_Controller”,
    data : $(‘#form2′).serialize(),
    success : function(response) {
    alert(“Submitted comment”);
    // window.location.reload(true);
    },
    error : function() {
    alert(“There was an error submitting comment”);
    } });
    window.close();
    });
    This send request to Servlet.
    In IE it works but in mozila post request is not go to Servlet doPost().
    But Mozila works with get request.
    I wat to sent post request so what is prob?

  • Vemula Ashok 2 April, 2014, 12:28

    $(document).ready(function(){
    $(“#form1″).submit(function(event) {
    alert(“Thank you for your comment!”);

    //event.preventDefault();

    $.ajax({
    type : “GET”,
    traditional: true,
    url : “/security/twelvehrspattern.html”,
    dataType: ‘json’,
    cache: false,
    async:true,
    data : “empidlist=”+empidlist+”&empnamelist=”+empnamelist+”&noofduties=”+noofduties,
    contentType: “application/json; charset=utf-8″,
    success : function(response) {
    console.log(“success”);
    alert(response);

    },
    error : function(e) {
    alert(‘Error: ‘ + e);
    }
    });
    });

  • Vemula Ashok 2 April, 2014, 12:30

    i am not able to pass the arrays of values to the spring controller alert(‘Error: ‘ + e); part is execution ,I need Help..Thanks in advance

  • SanjoS 19 June, 2014, 19:26

    Checking this site

  • SanjoS 19 June, 2014, 19:27

    page is not getting refresh while doing the same

  • ray jhon 31 July, 2014, 14:47

    Plz tell me
    —————–
    IN JSP PAGE:—-trying to passsing req to above code…

    $(“#id_complaint”).change(function(){
    var v_ttType = $(“#id_complaint”).val();
    alert(v_ttType);
    $.getJSON(“./attributeListcreateTT.*”,{TTType:v_ttType,ajax:’true’}, function(resp)
    {
    alert(‘in json’);
    for(var i=0;i<resp.length;i++)
    {
    alert(resp[i].ATTRIBUTE);
    alert(resp[i].OUTCOME);
    }

    });

    });
    });

    ————
    in action class

    public String attributeList()
    {
    //templist2=(ArrayList)CnmRefData.getTTAttributes(prod, ttType);

    //return templist2;

    System.out.println("in attributeList………………RequestCAme….");
    try{

    JSONObject object = null;
    JSONArray array = null;
    List jsonAttrList = new ArrayList();
    String ttType = httpServletRequest.getParameter(“TTType”);

    System.out.println(“In *>>> ::”+ttType);

    templist2=(ArrayList)CnmRefData.getTTAttributes(“RON”, ttType);

    System.out.println(“::::”+templist2.size());
    Iterator itr = templist2.iterator();
    while(itr.hasNext()){
    CNMTTAttribute objCNMTTAttribute = (CNMTTAttribute)itr.next();
    object = new JSONObject();
    object.put(“ATTRIBUTE”, objCNMTTAttribute.getAttribute());
    object.put(“OUTCOME”,objCNMTTAttribute.getValidateOutcome());
    jsonAttrList.add(object);
    }
    array = JSONArray.fromObject(jsonAttrList);

    response.setHeader(“Cache-Control”,”no-cache”);
    response.getWriter().write(array.toString());

    }catch(NullPointerException e){
    addActionError(e.getMessage());
    e.printStackTrace();
    }catch(RuntimeException e){
    addActionError(e.getMessage());
    e.printStackTrace();
    }catch(OutOfMemoryError e){
    addActionError(e.getMessage());
    e.printStackTrace();
    }catch(Exception e){
    addActionError(e.getMessage());
    e.printStackTrace();
    }
    return null;

    }

    please tell me what’s wrong… req not comming to action…..

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current day month ye@r *