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.

View Comments

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

  • 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

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

    Luis

  • 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");

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

    [code language="js"]
    $(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();

    });

    });
    [/code]

    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..)
    [code language="js"]
    success: function(){
    $("loading").html("here i am");
    }
    [/code]
    thanks in advance

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

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

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

  • 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

  • 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

Share
Published by
Viral Patel
Tags: AJAX JavaScript JQuery Tutorial

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago