Ajax POST request with parameters

Jquery Ajax Api Call Example with Live API Step by Step

In this article, we’ll discuss how to make Ajax requests using the Jquery Ajax function. In Jquery we’ve got several functions available to issue Ajax requests. We’ve got a load, get, and post.

All these functions i.e load, get, and post they actually call the Jquery Ajax function. These wrapper methods are easier to use, but they do not provide much flexibility.

If you want to have complete control and configure the behavior of the Ajax request, then use the Ajax method. Here is the syntax of the Ajax method.

jquery ajax api call example

We pass a single JavaScript object, and this object is going to contain all the options that define the behavior of the Ajax request. If you want to know the complete list of options available, then visit Jquery documentation URL.

it will look like the below image.

rest api ajax post example

So on this page, we have all the options available that we can use with this Jquery Ajax

I have a rest API that returns the list of tourists in a travel agency.Below is the response of API.

Now I want to fetch data from API and display it in HTML Table for that I’m going to use the ajax function.

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

Response:

{
  "$id": "1",
  "page": 1,
  "per_page": 10,
  "totalrecord": 3319,
  "total_pages": 332,
  "data": [
    {
      "$id": "2",
      "id": 1,
      "name": "ashish thapliyal",
      "email": "Ashulive6123@gmail.com",
      "profilepicture": "http://restapi.adequateshop.com/Media/Images/1a30600f-3b07-4797-b883-981b455f2e84.png",
      "location": "USA",
      "createdat": "2020-04-26T12:21:05.7103885"
    },
    {
      "$id": "3",
      "id": 2,
      "name": "traveler change name",
      "email": "travel11@gmail.com",
      "profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "location": "USA",
      "createdat": "2020-04-26T12:21:42.8669234"
    },
    {
      "$id": "4",
      "id": 3,
      "name": "Anand Prakash",
      "email": "1661677300651859",
      "profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "location": "USA",
      "createdat": "2020-04-26T12:23:38.8303108"
    },
    {
      "$id": "5",
      "id": 6,
      "name": "Vikash Kumar Shah",
      "email": "adktest12@gmail.com",
      "profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "location": "USA",
      "createdat": "2020-04-26T15:02:16.6330683"
    },
    {
      "$id": "6",
      "id": 7,
      "name": "Raju Prasad",
      "email": "raju.nsit@gmail.com",
      "profilepicture": "http://restapi.adequateshop.com/Media/Images/5e914f8f-7eb7-4895-838f-09e0fe4afda1.png",
      "location": "Delhi Noida Direct Flyway, New Friends Colony, New Delhi, Delhi 110024, India",
      "createdat": "2020-04-26T15:44:01.3315904"
    },
    {
      "$id": "7",
      "id": 8,
      "name": "Adequate Infosoft",
      "email": "contact@adequateinfosoft.com",
      "profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "location": "USA",
      "createdat": "2020-04-26T17:17:15.2711201"
    },
    {
      "$id": "8",
      "id": 9,
      "name": "Ashok Patel",
      "email": "ashokpatel457@gmail.com",
      "profilepicture": "http://restapi.adequateshop.com/Media/UserProfileCover/9/11ee4354-89d5-48c2-8edc-900e0d5fa93f.png",
      "location": "Noida, Uttar Pradesh, India",
      "createdat": "2020-04-26T17:17:47.4475925"
    },
    {
      "$id": "9",
      "id": 10,
      "name": "Vikash Shah",
      "email": "1564091363743796",
      "profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "location": "USA",
      "createdat": "2020-04-26T17:31:22.4311495"
    },
    {
      "$id": "10",
      "id": 11,
      "name": "Brigette Jewell",
      "email": "brigettejewell.90897@gmail.com",
      "profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "location": "USA",
      "createdat": "2020-04-26T18:42:50.4394587"
    },
    {
      "$id": "11",
      "id": 14,
      "name": "Pankaj Joshi",
      "email": "adeq4201@yopmail.com",
      "profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
      "location": "USA",
      "createdat": "2020-04-29T06:50:28.5461077"
    }
  ]
}

Rest API Ajax GET example

<!DOCTYPE html>
<html>
<head>
    <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>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
<body>

    <div class="container">
        <h1> Calling rest api from javascript/jquery </h1>
        <br />
        <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>
    </div>
</body>
</html>

<script type="text/javascript">
    $(document).ready(function () {
        GetallTourist()
    });
    //add customer
    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].profilepicture + ">" + result.data[i].name + "</td>"

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

calling rest api from javascript example

Specify the URL to which you want to make a request, then you use this URL option. If you want to specify whether you want to issue a GET or a POST request, then you have a method option.

you want to issue a get request, you specify GET. If it is post, then specify POST. Similarly, if you want to call a function when the request completes successfully, then you have this success option.

If there is an error processing the request, and if you want to handle the error, you can specify a callback function using the error option.

Ajax call rest API with parameters

Ajax GET example with parameters, Let’s take an example where we need to pass the parameter in the rest API.

Api Url:  http://restapi.adequateshop.com/api/Tourist/7

Json Response:

{
  "$id": "1",
  "id": 7,
  "name": "Mark Henry",
  "email": "test@mailnitor.com",
  "profilepicture": "http://restapi.adequateshop.com/Media/Images/71161727-fee8-478f-8b8f-aba7d1545ef4.png",
  "location": "Delhi Noida Direct Flyway, New Friends Colony, New Delhi, Delhi 110024, India",
  "createdat": "2020-04-26T15:44:01.3315904"
}

API Calling:

<!DOCTYPE html>
<html>
<head>
    <title> Use of JQuery to Add Edit Delete Table Row </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>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
<body>

    <div class="container">
        <h1> Calling rest api from javascript/jquery </h1>
        <br />
        <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>
    </div>
</body>
</html>

<script type="text/javascript">
    $(document).ready(function () {
        GetallTourist()
    });
    //add customer
    function GetallTourist()
    {
        $.ajax({
            url: 'http://restapi.adequateshop.com/api/Tourist/3',
            method: 'GET',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                debugger;
                if(result!=null)
                {
                   var tablerow = "<tr>"
                                      + "<td>"+ result.id + "</td>"
                                      + "<td>" + "<img style='width:20px;border-radius:50px' src=" + result.profilepicture + ">" + result.name + "</td>"
                                      + "<td>" + result.email + "</td>"
                                      + "<td>" + result.location + "</td>"
                                      + "</tr>";
                    $("#tblbody").append(tablerow);
                }
            },
            fail: function (jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            }
        })
    }
</script>

Ajax call rest api with parameters

Ajax POST request with parameters example

So now let’s look at an example of using this Jquery Ajax function with the post.

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

Parameters

{

  "name": "jack",
  "email": "jack435@gmail.com",  
  "location": "London"
}

Response

{
  "$id": "1",
  "id": 12407,
  "name": "jack",
  "email": "jack435@gmail.com",
  "profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
  "location": "London",
  "createdat": "2021-12-06T08:39:03.6119627Z"
}

API Calling:

 //getting values from control
    var txtName = $("#txtName").val();
    var txtEmail = $("#txtEmail").val();
    var Address = $("#txtAddress").val();

    var tarvelerobj = {};
    tarvelerobj.name = txtName;
    tarvelerobj.email = txtEmail;
    tarvelerobj.location = Address;
    $.ajax({
        url: 'http://restapi.adequateshop.com/api/Tourist',
        method: 'POST', //HTTP POST
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(tarvelerobj), //sending data to the sever
        success: function (data) {
            //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.profilepicture + ">" + data.name + "</td>"

                + "<td>" + data.email + "</td>"
                + "<td>" + data.location + "</td>"
                + "</tr>";
            $("#tblbody").append(tablerow);
            $("#txtName").val('');
            $("#txtEmail").val('');
            $("#textarea").text('');
        },
        fail: function (jqXHR, textStatus) {
            alert("Request failed: " + textStatus);
        }
    })

jQuery ajax post json example

I have created a form for making the entry in the database table.On button click, I’m calling the POST api for creating the entry in the database. On successful call of the, 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>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</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="txtName" id="txtName" class="form-control" value="" required="">
            </div>
            <div class="form-group">
                <label>Email:</label>
                <input type="email" name="txtEmail" id="txtEmail" class="form-control" value="" required="">
            </div>
            <div class="form-group">
                <label>Location:</label>
                <textarea class="form-control" name="txtAddress" id="txtAddress"></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 = $("#txtName").val();
        var txtEmail = $("#txtEmail").val();
        var Address = $("#txtAddress").val();

        var tarvelerobj = {};
        tarvelerobj.name = txtName;
        tarvelerobj.email = txtEmail;
        tarvelerobj.location = Address;
        $.ajax({
            url: 'http://restapi.adequateshop.com/api/Tourist',
            method: 'POST', //HTTP POST
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(tarvelerobj), //sending data to the sever
            success: function (data) {
                //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.profilepicture + ">" + data.name + "</td>"

                    + "<td>" + data.email + "</td>"
                    + "<td>" + data.location + "</td>"
                    + "</tr>";
                $("#tblbody").append(tablerow);
                $("#txtName").val('');
                $("#txtEmail").val('');
                $("#textarea").text('');
            },
            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].profilepicture + ">" + result.data[i].name + "</td>"

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

Ajax PUT Request Jquery Example

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

Parameters:

{
  "id": 7,
  "name": "update name",
  "email": "update@gmail.com",
  "location": "paris",
}

Response:

{
  "$id": "1",
  "id": 7,
  "name": "update name",
  "email": "update@gmail.com",
  "profilepicture": "http://restapi.adequateshop.com/Media/Images/71161727-fee8-478f-8b8f-aba7d1545ef4.png",
  "location": "paris",
  "createdat": "2020-04-26T15:44:01.3315904"
}

API Calling:

var txtId = $("#txtId").val();
    var txtName = $("#txtName").val();
    var txtEmail = $("#txtEmail").val();
    var Address = $("#txtAddress").val();

    var tarvelerobj = {};
    tarvelerobj.id = txtId;
    tarvelerobj.name = txtName;
    tarvelerobj.email = txtEmail;
    tarvelerobj.location = Address;
    $.ajax({
        url: 'http://restapi.adequateshop.com/api/Tourist/' + txtId,
        method: 'PUT',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(tarvelerobj),
        success: function (data) {
            alert("Saved successfully");
        },
        fail: function (jqXHR, textStatus) {
            alert("Request failed: " + textStatus);
        }
    })

jQuery ajax PUT json example

<!DOCTYPE html>
<html>
<head>
    <title> jQuery Ajax PUT request body </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>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
<body>

    <div class="container">
        <h1> jQuery Ajax PUT request body </h1>
        <form id="addcustomerform">
            <div class="form-group">
                <label>Id:</label>
                <input type="text" name="txtId" id="txtId" readonly class="form-control" value="" required="">
            </div>
            <div class="form-group">
                <label>Name:</label>
                <input type="text" name="txtName" id="txtName" class="form-control" value="" required="">
            </div>
            <div class="form-group">
                <label>Email:</label>
                <input type="email" name="txtEmail" id="txtEmail" class="form-control" value="" required="">
            </div>
            <div class="form-group">
                <label>Location:</label>
                <textarea class="form-control" name="txtAddress" id="txtAddress"></textarea>
            </div>
            <button type="submit" id="btnupdatetraveler" class="btn btn-primary save-btn">Update Traveler</button>
        </form>
        <br />
    </div>
</body>
</html>
<script type="text/javascript">
    $(document).ready(function () {
        GetallTouristById()
    });

    //update traveler
    $("#btnupdatetraveler").on("click", function (e) {
        e.preventDefault();
        var txtId = $("#txtId").val();
        var txtName = $("#txtName").val();
        var txtEmail = $("#txtEmail").val();
        var Address = $("#txtAddress").val();

        var tarvelerobj = {};
        tarvelerobj.id = txtId;
        tarvelerobj.name = txtName;
        tarvelerobj.email = txtEmail;
        tarvelerobj.location = Address;
        $.ajax({
            url: 'http://restapi.adequateshop.com/api/Tourist/' + txtId,
            method: 'PUT',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(tarvelerobj),
            success: function (data) {
                alert("Saved successfully");
            },
            fail: function (jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            }
        })
    });

    //Get All allTourist
    function GetallTouristById() {
        $.ajax({
            url: 'http://restapi.adequateshop.com/api/Tourist/3',
            method: 'GET',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                if (result != null) {
                    $("#txtId").val(result.id);
                    $("#txtName").val(result.name);
                    $("#txtEmail").val(result.email);
                    $("#txtAddress").val(result.location);
                }
            },
            fail: function (jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            }
        })
    }
</script>

JQuery Ajax DELETE request

<script type="text/javascript">
   
    function Deleterow()
    {
        $.ajax({
            url: 'http://restapi.adequateshop.com/api/Tourist/3',
            method: 'DELETE',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                alert("Deleted successfully");
            },
            fail: function (jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            }
        })
    }
</script>

Code Explanation:

Actually, if you look at this Jquery Ajax function IntelliSense, notice that it is showing URL and then options parameter.

Actually, this Ajax function has got two overloads. The first overload is one where you can specify URL parameters separately, and then all the options that you want to include.

And we have another overload here where you just pass the JavaScript object and specify all the options, including the URL.

Let’s go ahead and use the second overloaded version.  we are going to pass a JavaScript object, and here we are going to specify all the options. So first we want to specify the URL to which we want to issue a request. So I’m going to use the URL and then the URL itself.

And next, we want to specify the data that we want to pass to the server. So I’m going to use the data option and we have the object here.

Then we want to specify the type of request whether you want to issue a get or a post request, and to do that, I’m going to use the method option. So I want to issue a POST request.

And I also want to specify the type of data that we are going to get back from the server. Now to specify that I’m going to use the data type option, and we are actually going to get JSON data back. So let’s specify the data type as JSON.

Now, once the request is processed successfully, we want to handle that response and then display that within the UI elements. on success, I want to call a function so we can specify the callback function.

So that’s it. whatever we are doing here we are now doing using the Ajax function. So we have specified the URL specified the data that we want to pass to the server whether we want to issue a get a post request. Here we are using the post method. So it’s going to issue a post

That’s the reason we have specified the method as the post. In case if you want to show a get request, simply change it to get and the return type.

That is the type of data that we are expecting from the server as JSON. We have specified that here using the data type option. And here we have the success callback function, and we have that success callback function here.

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

Ashok Patel

I'm a software engineer, having good experience in software programming web designing with great command on ASP.NET, React JS, Angular JS,.NET Core HTML5, JavaScript, T-SQL, JQuery.
Also have great experience in Electronics and electrical engineers design.
I like to do RND and Research.

Add comment

Your Header Sidebar area is currently empty. Hurry up and add some widgets.