jQuery > Ajax methods

.post() & .get() - Get & Post request to server in jQuery

How to send request to and get response from server using HTTP Get and HTTP Post method in jQuery?


To send request to and get response from the server using HTTP Get and HTTP post, we can use post() and get() methods respectively. In this way also browser post back doesn?t happen.

Post()

  <input type="button" id="btnPost" value="Load Data using Post" />
    <div id="divResult"></div>
    
    <script>
        $("#btnPost").click(function () {
            $.post(
            "jQueryAjaxData.aspx",
            { a: "20", b: "6" },
            function (data) {
                $("#divResult").html("<b>The result is: " + data + "</b>");
            });
        });
    </script>

This is similar to .ajax method however this guarantees that ajax request will be sent to the server using html form post method only. Here are the parameters to pass

  • 1st parameter is the url to post data
  • 2nd parameter is the data to be posted. Note that parameter should be specified in the curly braces and key and value should be separated with “:” (colon)
  • 3rd  will be the function to execute after successful request. Here “data” will have all the response string returned by jQueryAjaxData.aspx page
To retrieve data sent to jQueryAjaxData.aspx page, we can use Request.Form like below
 
var a = Request.Form["a"]; // a value will be 20
var b = Request.Form["b"]; // b value will be 6

Get()

   <input type="button" id="btnGet" value="Load Data using Get" />
   <div id="divResult"></div>
    
    <script>
        $("#btnGet").click(function () {
            $.get(
            "jQueryAjaxData.aspx",
            { ag: "2", bg: "6" },
            function (data) {
                $("#divResult").html("<b>The result is: " + data + "</b>");
            });
        });
    </script>

This is similar to .ajaxmethod however this guarantees that ajax request will be sent to the server using html form get method. The only difference between Post and Get is the method by which data is submitted to the page.

Here

  • 1st parameter is the url to post data
  • 2nd parameter is the data to be posted. Note that parameter should be specified in the curly braces and key and value should be separated with “:” (colon)
  • 3rd parameter will be the function to execute after successful request. Here “data” will have all the response string returned by jQueryAjaxData.aspx page.
To retrieve data sent to jQueryAjaxData.aspx page, we can use Request.QueryString like below
 
var a = Request.QueryString["ag"]; // the value will be 2
var b = Request.QueryString["bg"]; // the value will be 6
 Views: 9648 | Post Order: 108



Write for us






Hosting Recommendations