jQuery Post Complete Guide for Beginners and Experts – Examples & Codes

jQuery Post Complete Guide for Beginners and Experts – Examples & Codes

The jQuery Post function is an AJAX method that fetches data from the server using HTTP POST. You can use it to call server page like .php or .aspx.

Let us understand all about the jQuery Post method in details.

Syntax of jQuery Post Method

jQuery.post( url [, data ] [, success ] [, dataType ] )

Name Value
url Required Parameter – URL to where AJAX request is made.
Data Optional parameter – it’s the key-value pairs that will be send with the AJAX request. Eg {Name: “Trump”,Job: “President of USA”}
success(result,status,xhr) Optional Parameter – the function that will be called on successful AJAX request. This function has 3 parameters which are all optional. Through the result parameter gets the return value from the AJAX request.
dataType Optional Parameter – the type of data returned from the AJAX request. Can be xml, json, script, or html.
I can apply the different methods of Deferred Object to the jQuery Post method. This will help me to know when the Post method is completed or failed.

I apply 2 methods of deferred Object in my jQuery Post method. These are –

  • deferred.done() – called when the AJAX method is successful.
  • deferred.fail() – called if the AJAX method fails.

jQuery Post to Call a PHP Page

Let’s call a .php page using jQuery Post from an HTML page. I am asking users to enter their first and last name in the text boxes.

On the button click event these values are send to the .php page which sends back the welcome message.

Enter your First Name, Last Name and click button

HTML Page Code:

<input type="text" placeholder="First Name" id="firstName" />
<input type="text" placeholder="Last Name" id="lastName" />
<button id="submit">Try</button>
<div id="message"></div>
$("#submit").click(function (e) {
    $.post("result.php",
    {
        firstName: $("#firstName").val(),
        lastName: $("#lastName").val()
    })
    .done(function (result, status, xhr) {
        $("#message").html(result)
    })
    .fail(function (xhr, status, error) {
        $("#message").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
    });
});

The .php page takes down the 2 values (firstName & lastName) and send back the message(through echo), which is displayed by the HTML page.

<?php
$firstName = $_REQUEST['firstName'];
$lastName = $_REQUEST['lastName'];
echo "Welcome: ". $firstName . " " . $lastName;
?>
Capturing jQuery Post Error

Use .fail() deferred method to capture any errors that come during the AJAX request. The fail method can be attached to the Post() at the end. I have applied it to the examples given above.

jQuery Post to Call an ASP.NET Page

Let us show how jQuery Post works. There are 2 page one is the HMTL page that has 2 textboxes (for name and city) and a button, the other page is the .ASPX one.

On clicking the button the AJAX call is made to the .ASPX page which gets the values of the 2 textboxes through HTTP Post.

The HTML Page Code:

<input type="text" placeholder="Name" id="nameInput"/>
<input type="text" placeholder="City" id="cityInput"/>
<button id="submitButtonAsp">Try</button>
<div id="returnedData"></div><script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#submitButtonAsp").click(function (e) {
            $.post("result.aspx",
                {
                    name: $("#nameInput").val(),
                    city: $("#cityInput").val()
                },
                function (result, status, xhr) {
                    $("#returnedData").html(result);
                }
                ).fail(function (xhr, status, error) {
                    $("#returnedData").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
            });
        });
    }); 
</script>
In the above code you may have noticed how I have applied the “.fail()” function which gets called up if there is some error during AJAX call.

The .ASPX page gets the HTTP POST values and returns a custom welcome message.
The .ASPX Page Code:

if (!IsPostBack)
{
    string name = Request.Form["name"];
    string city = Request.Form["city"];

    Response.Write("Welcome Mr. " + name + " from " + city);
    Response.End();
}

To return the welcome message I have used “Response.Write()” method.

DEMO

jQuery Post to Fetch Data from Database

The jQuery Post can be used to fetch data from Database. For this first call a server page like .aspx or .php. Then from this page access and get data from DB. Finally return this data to the jQuery Post method.

Let us make a small application in asp.net that shows how it works. There are 2 pages in this application, these are –

  • 1. HTML page from where jQuery Post call is made. It has 2 dropdown controls whose values are passed with the jQuery Post method call.
  • 2. ASPX page is the other page which receives this call. This page receives the dropdown controls values. It fetches the corresponding data from DB and then returns it back.

HTML Page Code:

<select id="sportSelect">
    <option value="Select">Select Sports</option>
    <option value="Baseball">Baseball</option>
    <option value="Cricket">Cricket</option>
    <option value="Basketball">Basketball</option>
</select>
<select id="playerSelect">
    <option value="Select">Select Sports Person</option>
    <option value="Shoeless Joe Jackson">Shoeless Joe Jackson</option>
    <option value="Don Bradman">Don Bradman</option>
    <option value="Michael Jordan">Michael Jordan</option>
</select>
<button id="loadDatabase">Try</button>
<div id="dbData"></div>

Place the below jQuery Post Code on the HTML page.

$("#loadDatabase").click(function (e) {
    $.post("getdata.aspx",
        {
            sport: $("#sportSelect").val(),
            player: $("#playerSelect").val()
        },
        function (result, status, xhr) {
            $("#dbData").html(result);
        }
        ).fail(function (xhr, status, error) {
            $("#dbData").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
        });
    });

The jQuery Post calls the “getdata.aspx” page which fetches the data from DB and returns it back.

The “getdata.aspx“ Page Code:

List<MyDataBase> myDataBase;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        LoadData();
        SearchDatabase();
    }
}

void SearchDatabase()
{
    string sport = Request.Form["sport"];
    string player = Request.Form["player"];
    try
    {
        string information = myDataBase.FirstOrDefault(x => x.sport == sport & x.player == player).information;
        Response.Write(information);
        Response.End();
    }
    catch (Exception ex)
    {
        Response.Write("NO DATA");
        Response.End();
    }
}

void LoadData()
{
    myDataBase = new List<MyDataBase>();
    myDataBase.Add(new MyDataBase() { sport = "Baseball", player = "Shoeless Joe Jackson", information = "Joe Jackson was a top major league baseball player during the early 20th century who was ousted from the sport for his alleged role in game fixing." });
    myDataBase.Add(new MyDataBase() { sport = "Cricket", player = "Don Bradman", information = "Sir Donald George 'Don' Bradman, AC (27 August 1908 – 25 February 2001), often referred to as 'The Don', was an Australian cricketer, widely acknowledged as the greatest batsman of all time." });
    myDataBase.Add(new MyDataBase() { sport = "Basketball", player = "Michael Jordan", information = "Michael Jordan is the greatest basketball player of all time. Jordan was one of the most effectively marketed athletes of his generation and was considered instrumental in popularizing the NBA around the world in the 1980s and 1990s" });
}

class MyDataBase
{
    public string sport { get; set; }
    public string player { get; set; }
    public string information { get; set; }
}

DEMO DOWNLOAD

Highly related topics of AJAX in jQuery:

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on “WordPress, SEO, jQuery, HTML” and more.