How To Pass Parameters in AJAX POST? | JQuery Ajax Post Json Example


AJAX is considered one of the most viable Rich Internet Application (RIA) technologies to date. It is rapidly gaining traction in the industry, with numerous toolkits and frameworks emerging from it. However, AJAX faces browser incompatibility issues and relies on JavaScript, which can be challenging to maintain and debug.

In the previous article, we discussed an example of using jQuery AJAX with GET parameters. In this post, we will explore how to utilize jQuery to send JSON data via POST requests.

How can I use JQuery to post JSON data?

To demonstrate, I've set up a POST REST service for testing purposes. Below, you'll find the request and response of the service. We'll use the following AJAX code to post JSON data to the service.

API Url: http://samplerestapi.com/api/Tourist

Parameters

{
    "tourist_name": "anuj",
    "tourist_email": "[email protected]",
    "tourist_location": "Noida 63",
}

Response

{
    "id": 17546,
    "tourist_name": "anuj",
    "tourist_email": "[email protected]",
    "tourist_profilepicture": "http://samplerestapi.com/Media//Images/userimageicon.png",
    "tourist_location": "Noida 63",
    "createdat": "2022-01-30T05:04:13.1664327Z"
}

Ajax Post API Calling:

Now, let's look into an example of using the jQuery Ajax function with a POST request. Firstly, specify the URL to which you intend to make the request using the 'url' option. Then, determine whether you want to issue a GET or a POST request. For a GET request, specify 'GET', and for a POST request, specify 'POST'. 

To handle the completion of the request successfully, utilize the 'success' option within the Ajax method. Conversely, if any errors occur during the request, the 'error' option is available.

The Ajax function comes with two overloads. The first overload allows you to specify URL parameters separately, followed by all the options you wish to include in the Ajax request.

The second overload version of the Ajax request involves passing a JavaScript object and specifying all the options, including the URL.

 //getting values from control
var txtName = $("#txttourist_name").val();
var txtEmail = $("#txttourist_email").val();
var txtaddress = $("#txttourist_location").val();

var postobj = {};
        postobj.tourist_name = txtName;
        postobj.tourist_email = txtEmail;
        postobj.tourist_location = txtaddress;
        $.ajax({
            url: 'http://samplerestapi.com/api/Tourist',
            method: 'POST', //HTTP POST
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(postobj), //sending data to the sever
            success: function (data) {
                debugger;
//getting response from server
                alert("Saved successfully");
//Binding the newly created row into the database
var tablerow = "<tr>"
                    + "<td>" + data.id + "</td>"
                    + "<td>" + "<img style='width:20px;border-radius:50px' src=" + data.tourist_profilepicture + ">" + data.tourist_name + "</td>"

                    + "<td>" + data.tourist_email + "</td>"
                    + "<td>" + data.tourist_location + "</td>"
                    + "</tr>";
                $("#tblbody").append(tablerow);
                $("#txttourist_name").val('');
                $("#txttourist_email").val('');
                $("#txttourist_location").val('');
            },
            fail: function (jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            }
        })
In our example we use the second overloaded version, we are going to pass a JavaScript object, and specify all the options.

JavaScript code performs an AJAX POST request to a REST API endpoint, sending JSON data to the server and handling the response accordingly. Here's a breakdown:

The code extracts values from three input controls with IDs txttourist_name, txttourist_email, and txttourist_location, storing them in respective variables (txtName, txtEmail, txtaddress).

These values are then used to create a JavaScript object called postobj, which represents the data to be sent to the server. The object properties (tourist_name, tourist_email, tourist_location) are assigned the corresponding values extracted from the input controls.

The $.ajax() function is used to initiate the AJAX request. It specifies the URL of the REST API endpoint (url), the HTTP method (method), the data type expected from the server (dataType), and the content type of the request (contentType). Additionally, the data to be sent to the server is stringified using JSON.stringify() and passed as the data parameter.

Upon successful completion of the request, the success callback function is executed. Inside this function, the response data from the server is accessed, and an alert message indicating successful saving is displayed. Furthermore, the response data is used to dynamically generate HTML for a table row (tablerow). This row is then appended to the table body (#tblbody). Finally, the input controls are cleared.

In case of a failure in the request, the fail callback function is executed, displaying an alert message indicating the failure along with the status text.

This code demonstrates how to use jQuery's AJAX function to send data to a server, handle the response, and update the UI accordingly, all within the context of a web application.

So the first parameter is the URL to which we want to issue a POST request I’m going to use the URL option of ajax request for that.

After that we need to specify the type of HTTP request i.e we want to issue a get or a post request, and to do that, I’m going to use the method option of the ajax function. as we want to issue a POST request I have specified it POST.

And then we want to specify the data that we want to pass to the rest API server. For that, I’m going to use the data option of the Ajax method.

we also need to specify the type of data that we are going to get back from the server response when calling success.
Now to specify we are using the datatype option, I have set datatype to JSON i.e we are specifying that we get JSON data back from the server.

Now, once the request is completed successfully, we want to handle that response and then want to display that information in the HTML.
that means on the success of the ajax request, we will populate the HTML table.

So we have specified the URL, specified the JSON data that we want to post to the server also mention HTTP request type i.e we want to issue a get a post request. As we know that in this post ,we are taking about ajax post so we are using the post method.

Thank you for reading and have a great day if you have a question please comment.

jQuery Ajax Post json Example

Now let’s take and real-time example of ajax post request.I have created a form for making the entry in the database table.

On button click, I’m calling the POST api using ajax for creating the entry in the database. On successful call of the Api, we are appending the newly added row in the table

Ajax POST request with parameters

<!DOCTYPE html>
<html>
<head>
    <title> Ajax POST request with parameters example  </title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>

    <div class="container">
        <h1> Ajax POST request with parameters example </h1>
        <form id="addcustomerform">
            <div class="form-group">
                <label>Name:</label>
                <input type="text" name="txttourist_name" id="txttourist_name" class="form-control" value="" required="">
            </div>
            <div class="form-group">
                <label>Email:</label>
                <input type="email" name="txttourist_email" id="txttourist_email" class="form-control" value="" required="">
            </div>
            <div class="form-group">
                <label>Location:</label>
                <textarea class="form-control" name="txttourist_location" id="txttourist_location"></textarea>
            </div>
            <button type="submit" id="btnaddtraveler" class="btn btn-primary save-btn">add Traveler</button>
            <fieldset>
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>TouristName</th>
                            <th>TouristEmail</th>
                            <th>Location</th>
                        </tr>
                    </thead>
                    <tbody id="tblbody"></tbody>
                </table>
            </fieldset>
        </form>
        <br />
    </div>
</body>
</html>
<script type="text/javascript">
    $(document).ready(function () {
        GetallTourist()
    });

//add traveler
    $("#btnaddtraveler").on("click", function (e) {
        e.preventDefault();//prevent default form submission on button click

//getting values from control
var txtName = $("#txttourist_name").val();
var txtEmail = $("#txttourist_email").val();
var txtaddress = $("#txttourist_location").val();

var postobj = {};
        postobj.tourist_name = txtName;
        postobj.tourist_email = txtEmail;
        postobj.tourist_location = txtaddress;
        $.ajax({
            url: 'http://samplerestapi.com/api/Tourist',
            method: 'POST', //HTTP POST
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(postobj), //sending data to the sever
            success: function (data) {
                debugger;
//getting response from server
                alert("Saved successfully");
//Binding the newly created row into the database
var tablerow = "<tr>"
                    + "<td>" + data.id + "</td>"
                    + "<td>" + "<img style='width:20px;border-radius:50px' src=" + data.tourist_profilepicture + ">" + data.tourist_name + "</td>"

                    + "<td>" + data.tourist_email + "</td>"
                    + "<td>" + data.tourist_location + "</td>"
                    + "</tr>";
                $("#tblbody").append(tablerow);
                $("#txttourist_name").val('');
                $("#txttourist_email").val('');
                $("#txttourist_location").val('');
            },
            fail: function (jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            }
        })


    });
//Get All allTourist
    function GetallTourist() {
        $.ajax({
            url: 'http://samplerestapi.com/api/Tourist',
            method: 'GET',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                debugger;
if (result != null && result.data) {
for (var i = 0; i < result.data.length; i++) {
var tablerow = "<tr>"
                            + "<td>" + result.data[i].id + "</td>"
                            + "<td>" + "<img style='width:20px;border-radius:50px' src=" + result.data[i].tourist_profilepicture + ">" + result.data[i].tourist_name + "</td>"

                            + "<td>" + result.data[i].tourist_email + "</td>"
                            + "<td>" + result.data[i].tourist_location + "</td>"
                            + "</tr>";
                        $("#tblbody").append(tablerow);
                    }
                }
            },
            fail: function (jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            }
        })
    }
</script>

JQuery Ajax Post Json Example

*Thank you so much if you have a question please comment

Asynchronous web pages

In a traditional web model, when a web browser requests a web page and the web server responds to it as the requested web page. As soon as the page is loaded in your browser, the connection between the web browser and the webserver gets terminated.

and then a request is made for another page and the same process is followed back.
Whenever a request is sent by the user for a page, the existing page has to be reloaded to show the new information, only after the page is reloaded, new information or a new page will be shown. Sometimes this process is annoying for the user experience.

If you are making a big web application like youtube, then there will be a lot of web elements in it. In such a situation, if the page is reloaded repeatedly while interacting with every small element, then your web application will create a bad user experience.

For example, you are watching a video on youtube, you like this video and you click on the like button to like it, then if you click on the like button, the whole page is reloaded so that you do not want to like |

Asynchronous web pages are such web pages, some elements of which do not require the entire page to be loaded to be updated or loaded. The new content is dynamically loaded on the web page. Processing in such pages is done in the background.

User does not interface with this processing, how this happens, you will be told further in the Working of AJAX section.