AJAX is the most Viable Rich Internet Application (RIA) technology ever. It is gaining tremendous industry speed and many tool kits and frameworks are coming out of it. But at the same time, AJAX has browser incompatibility and it is supported by JavaScript which is difficult to maintain and debug.

In the previous article, we have discussed the jQuery Ajax GET Example with Parameters, In this post, We will discuss How can I use JQuery to post JSON data.

How can I use JQuery to post JSON data?

For showing you I have created post rest for the testing purpose, below is the request and response of the service. I want to post JSON to the service and for that we can use below Ajax Code.

API Url: http://restapi.adequateshop.com/api/Tourist

Parameters

{
  "tourist_name": "anuj",
  "tourist_email": "anuj45@gmail.com",
  "tourist_location": "Noida 63",
}

Response

{
  "id": 17546,
  "tourist_name": "anuj",
  "tourist_email": "anuj45@gmail.com",
  "tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
  "tourist_location": "Noida 63",
  "createdat": "2022-01-30T05:04:13.1664327Z"
}

Ajax Post API Calling:

So now let’s look at an example of using Jquery Ajax function with the post. Specify the URL to which you want to make a request, then you use this URL option. Specify whether you want to issue a GET or a POST request.you want to issue a get request, you specify GET. If it is POST, then specify POST. For calling a function when the request completes successfully, we have a successful option in the Ajax method. If any error occurred in the request, then we have the error option.

Ajax function has two overloads, The first overload is one in which you can specify URL parameters separately, and then all the options that you want to include in the ajax request.

And then we have another overload version of the ajax request in which you just pass the JavaScript object and specify 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://restapi.adequateshop.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.

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://restapi.adequateshop.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://restapi.adequateshop.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.

The post How to Pass Parameters in AJAX POST?| JQuery Ajax Post Json Example appeared first on Software Development | Programming Tutorials.



Read More Articles