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);
Code language: JavaScript (javascript)
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);
Code language: JavaScript (javascript)
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);
Code language: JavaScript (javascript)
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");
Code language: JavaScript (javascript)
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); } );
Code language: JavaScript (javascript)
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.
Get our Articles via Email. Enter your email address.

You may also like...

26 Comments

  1. Nalin says:

    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.

  2. 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

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

    Luis

  4. 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");

  5. idrish says:

    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

    • pradeep says:

      return false;
      or
      e.preventDefault();
      both cnnot be used together

  6. plr store says:

    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.

  7. scripty says:

    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?

  8. fati says:

    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?

  9. kedar says:

    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

  10. sumit kumar jain pithani says:

    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

  11. Vimal says:

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

  12. Selva C says:

    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 says:

      Hi Selva did you find something on your problem, it yes the can u plz mail me @ [email protected]

  13. jasmin says:

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

  14. Mary says:

    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?

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

  16. keffy says:

    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

  17. Aditi says:

    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?

  18. Vemula Ashok says:

    $(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);
    }
    });
    });

  19. Vemula Ashok says:

    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

  20. SanjoS says:

    Checking this site

  21. SanjoS says:

    page is not getting refresh while doing the same

  22. ray jhon says:

    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…..

  23. xzcvxv says:

    yo man

  24. nilofar says:

    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.

Leave a Reply

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