How to Consume ASP.NET Core API in jQuery

How to Consume ASP.NET Core API in jQuery

In my ASP.NET Core tutorial on API Controllers I created a REST API which does the CRUD operations on Reservation objects. Now in this tutorial I will consume that API in jQuery.

Make sure to keep the API project in running state so that the API can be consumed by jQuery.

So let’s start with any delay.

Get All Reservations

The API method called here is:

[HttpGet]
public IEnumerable<Reservation> Get()
{
//…
}

Create an HTML page called AllReservation.html, here in this page all the reservations will be shown.

These Reservations will be received from the API and will be shown in an HTML table.

So in this page create a table as shown below:

<table class="table table-sm table-striped table-bordered m-2">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Start Location</th>
            <th>End Location</th>
            <th>Update</th>
            <th>Delete</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

Notice I specifically kept the tbody element as empty, this is because with jQuery I will show the reservations inside it.

Next, add the following jQuery code to the page:

$(document).ready(function () {
    ShowAllReservation();

    function ShowAllReservation() {
        $("table tbody").html("");
        $.ajax({
            url: "http://localhost:8888/api/Reservation",
            type: "get",
            contentType: "application/json",
            success: function (result, status, xhr) {
                $.each(result, function (index, value) {
                    $("tbody").append($("<tr>"));
                    appendElement = $("tbody tr").last();
                    appendElement.append($("<td>").html(value["id"]));
                    appendElement.append($("<td>").html(value["name"]));
                    appendElement.append($("<td>").html(value["startLocation"]));
                    appendElement.append($("<td>").html(value["endLocation"]));
                    appendElement.append($("<td>").html("<a href=\"UpdateReservation.html?id=" + value["id"] + "\"><img src=\"icon/edit.png\" /></a>"
                    appendElement.append($("<td>").html("<img class=\"delete\" src=\"icon/close.png\" />"));
                });
            },
            error: function (xhr, status, error) {
                console.log(xhr)
            }
        });
    }

    $("table").on("click", "img.delete", function () {
        var reservationId = $(this).parents("tr").find("td:nth-child(1)").text();

        $.ajax({
            url: "http://localhost:8888/api/Reservation/" + reservationId,
            type: "delete",
            contentType: "application/json",
            success: function (result, status, xhr) {
                ShowAllReservation();
            },
            error: function (xhr, status, error) {
                console.log(xhr)
            }
        });
    });

});
Understanding the Get Reservation code
I created a JavaScript function called ShowAllReservation() which contain the jQuery .ajax() method. This .ajax() method code is shown below:
$.ajax({
    url: "http://localhost:8888/api/Reservation",
    type: "get",
    contentType: "application/json",
    success: function (result, status, xhr) {
        $.each(result, function (index, value) {
            $("tbody").append($("<tr>"));
            appendElement = $("tbody tr").last();
            appendElement.append($("<td>").html(value["id"]));
            appendElement.append($("<td>").html(value["name"]));
            appendElement.append($("<td>").html(value["startLocation"]));
            appendElement.append($("<td>").html(value["endLocation"]));
            appendElement.append($("<td>").html("<a href=\"UpdateReservation.html?id=" + value["id"] + "\"><img src=\"icon/edit.png\" /></a>"
            appendElement.append($("<td>").html("<img class=\"delete\" src=\"icon/close.png\" />"));
        });
    },
    error: function (xhr, status, error) {
        console.log(xhr)
    }
}); 

Notice I am making an HTTP GET type of AJAX request to the API URL – ‘http://localhost:8888/api/Reservation’.

The API sends back all the reservations in JSON format which is shown below:

[
  {
    "id": 1,
    "name": "Ankit",
    "startLocation": "New York",
    "endLocation": "Beijing"
  },
  {
    "id": 2,
    "name": "Bobby",
    "startLocation": "New Jersey",
    "endLocation": "Boston"
  },
  {
    "id": 3,
    "name": "Jacky",
    "startLocation": "London",
    "endLocation": "Paris"
  }
]

Next, check the success callback of the .ajax() method, where I loop through this JSON and show the values inside the tbody element of the table.

As mentioned, I initially I kept the tbody element as empty.

Notice I also added an anchor and img elements for performing the ‘update’ and ‘delete’ of the reservations:

appendElement.append($("<td>").html("<a href=\"UpdateReservation.html?id=" + value["id"] + "\"><img src=\"icon/edit.png\" /></a>"
appendElement.append($("<td>").html("<img class=\"delete\" src=\"icon/close.png\" />"));
Test the functionality

Double click the ‘AllReservation.html’ page to open it in your browser. It will show all the reservation fetched from the API. Check the below image which shows how the reservations are displayed on the table:

all reservations

Delete a Reservation

The API method called here is:

[HttpDelete("{id}")]
public void Delete(int id) => repository.DeleteReservation(id); 
I also created a click event for the img tag that has a ‘delete’ class. Then inside this event I will make an API call to delete a particular reservation. The code which does this work is given below:
$("table").on("click", "img.delete", function () {
    var reservationId = $(this).parents("tr").find("td:nth-child(1)").text();

    $.ajax({
        url: "http://localhost:8888/api/Reservation/" + reservationId,
        type: "delete",
        contentType: "application/json",
        success: function (result, status, xhr) {
            ShowAllReservation();
        },
        error: function (xhr, status, error) {
            console.log(xhr)
        }
    });
});
Understanding the Delete Reservation code
I created the click event using jQuery .on() method for the ‘img’ tag that has ‘delete’ class. This is because the ‘img’ tag is created dynamically. The first td element of any row gives the reservation id, which I get from the below code:
var reservationId = $(this).parents("tr").find("td:nth-child(1)").text();
Reference tutorial – jQuery nth child
After that I make the API call of type HTTP DELETE, to the API URL which contains the reservation id at the end:
url: "http://localhost:8888/api/Reservation/" + reservationId
Once the reservation gets deleted, then I call the ShowAllReservation() function in the success callback, so that the table is refreshed with the newest reservation data.
Test the functionality

Click the cross icon against any reservation object and the API will delete it. Check the below video which shows the delete process:

Delete a Reservation
Delete a Reservation

Add a Reservation

The API method called here is:

[HttpPost]
public IActionResult Post([FromBody] Reservation res)
{ 
//…
}
Now I will add a new Reservation by sending the reservation data in JSON to the API. So create a new HTML page called AddReservation.html and add the following html to it:
<div class="form-group">
    <label for="Name">Name:</label>
    <input type="text" class="form-control" id="Name" />
</div>
<div class="form-group">
    <label for="StartLocation">Start Location:</label>
    <input type="text" class="form-control" id="StartLocation" />
</div>
<div class="form-group">
    <label for="EndLocation">End Location:</label>
    <input type="text" class="form-control" id="EndLocation" />
</div>
<div class="text-center panel-body">
    <button type="submit" class="btn btn-sm btn-primary" id="AddButton">Add</button>
</div>

<div style="display:none" id="resultDiv">
    <h2>Reservation</h2>
    <table class="table table-sm table-striped table-bordered m-2">
        <thead><tr><th>ID</th><th>Name</th><th>Start Location</th><th>End Location</th></tr></thead>
        <tbody></tbody>
    </table>
</div>

There are 3 input controls for accepting the Name, Start Location and End Location of a new reservation:

<input type="text" id="Name" />
<input type="text" id="StartLocation" />
<input type="text" id="EndLocation" />

There is also a button, on whose click event the API call is made:

<button type="submit" class="btn btn-sm btn-primary" id="AddButton">Add</button>

Once, the reservation is added then the API will send the new reservation’s data in JSON format. I will show this data in the HTML table which is kept inside the hidded div:

<div style="display:none" id="resultDiv">
    <h2>Reservation</h2>
    <table class="table table-sm table-striped table-bordered m-2">
        <thead>
             <tr>            
                 <th>ID</th>
                 <th>Name</th>
                 <th>Start Location</th>
                 <th>End Location</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>

Next, add the following jQuery code to this page:

$("#AddButton").click(function (e) {
    $.ajax({
        url: "http://localhost:8888/api/Reservation",
        headers: {
            Key: "[email protected]"
        },
        type: "post",
        contentType: "application/json",
        data: JSON.stringify({
            Id: 0,
            Name: $("#Name").val(),
            StartLocation: $("#StartLocation").val(),
            EndLocation: $("#EndLocation").val()
        }),
        success: function (result, status, xhr) {
            var str = "<tr><td>" + result["id"] + "</td><td>" + result["name"] + "</td><td>" + result["startLocation"] + "</td><td>" + result[
            $("table tbody").append(str);
            $("#resultDiv").show();
        },
        error: function (xhr, status, error) {
            console.log(xhr)
        }
    });
});
Understanding the Add Reservation code

On the button click event I make an AJAX request to the API URL – ‘http://localhost:8888/api/Reservation’.

Since the API will need Credentials for adding a reservation, therefore these credentials are added to the HTTP Header like shown below:

headers: {
    Key: "[email protected]"
}
Check the API Post method (which is called by this AJAX request). It contains the [FromBody] attribute for the reservation parameter:
[HttpPost]
public IActionResult Post([FromBody] Reservation res)
{
  //…
}
Therefore in my jQuery code, I used the data parameter of the .ajax() method, and send the new reservation values by using the JSON.stringify() method:
data: JSON.stringify({
    Id: 0,
    Name: $("#Name").val(),
    StartLocation: $("#StartLocation").val(),
    EndLocation: $("#EndLocation").val()
})
Once the reservation is added, the API sends back the response which contains the newly added reservation object, which is shown inside the tbody element of the table:
success: function (result, status, xhr) {
    var str = "<tr><td>" + result["id"] + "</td><td>" + result["name"] + "</td><td>" + result["startLocation"] + "</td><td>" + result[
    $("table tbody").append(str);
    $("#resultDiv").show();
},
Test the functionality
Run the page in your browser and you will be able to add a new reservation just like what is shown by the below video:
add a reservation

Update a Reservation

The API has 2 methods to update a reservation. First method accepts an HTTP PUT type of request while the second method accepts an HTTP PATCH type of request.

I will show you how to invoke each of these 2 methods with jQuery.

Invoking HTTP PUT type API method

The HTTP PUT type of API method which will be called here is:
[HttpPut]
public Reservation Put([FromForm] Reservation res)
{
//…
}
Start by creating a new HTML page called UpdateReservation.html. Then add the following HTML to this page:
<div class="form-group">
    <label asp-for="Id"></label>
    <input type="text" class="form-control" id="Id" readonly />
</div>
<div class="form-group">
    <label for="Name">Name:</label>
    <input type="text" class="form-control" id="Name" />
</div>
<div class="form-group">
    <label for="StartLocation">Start Location:</label>
    <input type="text" class="form-control" id="StartLocation" />
</div>
<div class="form-group">
    <label for="EndLocation">End Location:</label>
    <input type="text" class="form-control" id="EndLocation" />
</div>
<div class="text-center panel-body">
    <button type="submit" class="btn btn-sm btn-primary" id="UpdateButton">Update</button>
</div>

<div style="display:none" id="resultDiv">
    <h2>Reservation</h2>
    <table class="table table-sm table-striped table-bordered m-2">
        <thead><tr><th>ID</th><th>Name</th><th>Start Location</th><th>End Location</th></tr></thead>
        <tbody></tbody>
    </table>
</div>

There are some input controls, where the reservation to be updated will first be fetched from the API, and shown in these input controls.

User will update the reservation by entering the updated values in these input controls, and clicking the button.

On clicking the button the reservation will be updated and the newly updated values are shown inside the HTML table.

Next add the following jQuery code to this page:

$(document).ready(function () {
    GetReservation();

    function GetReservation() {
        let params = (new URL(document.location)).searchParams;
        let id = params.get("id");

        $.ajax({
            url: "http://localhost:8888/api/Reservation/" + id,
            type: "get",
            contentType: "application/json",
            success: function (result, status, xhr) {
                $("#Id").val(result["id"]);
                $("#Name").val(result["name"]);
                $("#StartLocation").val(result["startLocation"]);
                $("#EndLocation").val(result["endLocation"]);
            },
            error: function (xhr, status, error) {
                console.log(xhr)
            }
        });
    }

    $("#UpdateButton").click(function (e) {
        let params = (new URL(document.location)).searchParams;
        let id = params.get("id");

        data = new FormData();
        data.append("Id", $("#Id").val());
        data.append("Name", $("#Name").val());
        data.append("StartLocation", $("#StartLocation").val());
        data.append("EndLocation", $("#EndLocation").val());

        $.ajax({
            url: "http://localhost:8888/api/Reservation",
            type: "put",
            data: data,
            processData: false,
            contentType: false,
            success: function (result, status, xhr) {
                var str = "<tr><td>" + result["id"] + "</td><td>" + result["name"] + "</td><td>" + result["startLocation"] + "</td><td>" + result[
                $("table tbody").append(str);
                $("#resultDiv").show();
            },
            error: function (xhr, status, error) {
                console.log(xhr)
            }
        });
    });
});
Understanding the Update Reservation code
The reservation id is send to this page in query string. To get this reservation id the following 2 lines of codes are used:
let params = (new URL(document.location)).searchParams;
let id = params.get("id");

So the variable called id now has the reservation id.

I then make the HTTP GET request to the API to fetch the reservation data of this particular ‘id’.

Check the URL of the API where the id is added to the end:

url: "http://localhost:8888/api/Reservation/" + id

Once I get the reservation data from the API I bind it to the input controls:

$("#Id").val(result["id"]);
$("#Name").val(result["name"]);
$("#StartLocation").val(result["startLocation"]);
$("#EndLocation").val(result["endLocation"]);
Now the UpdateButton click event updates the reservation. It makes the HTTP PUT type of request to the API method:
$.ajax({
    url: "http://localhost:8888/api/Reservation",
    type: "put",
    data: data,
    processData: false,
    contentType: false,
    success: function (result, status, xhr) {
        var str = "<tr><td>" + result["id"] + "</td><td>" + result["name"] + "</td><td>" + result["startLocation"] + "</td><td>" + result[
        $("table tbody").append(str);
        $("#resultDiv").show();
    },
    error: function (xhr, status, error) {
        console.log(xhr)
    }
});

Notice that I have put processData and contentType values to false:

processData: false
contentType: false

Also notice I send the updated reservation data to the API in FormData object:

data = new FormData();
data.append("Id", $("#Id").val());
data.append("Name", $("#Name").val());
data.append("StartLocation", $("#StartLocation").val());
data.append("EndLocation", $("#EndLocation").val());
Test the functionality

The functionality is shown by the below video:

update reservation put

Invoking HTTP PATCH type API method

The HTTP PATCH type of API method which will be called here is:

[HttpPatch("{id}")]
public StatusCodeResult Patch(int id, [FromBody]JsonPatchDocument<Reservation> patch)
{
//…
}

Create a new HTML page called <span class=”term”>UpdateReservationPatch.html</span>. Then add the following HTML to this page:

<div class="form-group">
    <label asp-for="Id"></label>
    <input type="text" class="form-control" id="Id" readonly />
</div>
<div class="form-group">
    <label for="Name">Name:</label>
    <input type="text" class="form-control" id="Name" />
</div>
<div class="form-group">
    <label for="StartLocation">Start Location:</label>
    <input type="text" class="form-control" id="StartLocation" />
</div>
<div class="form-group">
    <label for="EndLocation">End Location:</label>
    <input type="text" class="form-control" id="EndLocation" />
</div>
<div class="text-center panel-body">
    <button type="submit" class="btn btn-sm btn-primary" id="UpdateButton">Update</button>
</div>

There are input controls where the user can put the updated reservation values, and a button which on clicking will make the API call to update the reservation.

Now add the following jQuery code to this page:

$(document).ready(function () {
    GetReservation();

    function GetReservation() {
        let params = (new URL(document.location)).searchParams;
        let id = params.get("id");

        $.ajax({
            url: "http://localhost:8888/api/Reservation/" + id,
            type: "get",
            contentType: "application/json",
            success: function (result, status, xhr) {
                $("#Id").val(result["id"]);
                $("#Name").val(result["name"]);
                $("#StartLocation").val(result["startLocation"]);
                $("#EndLocation").val(result["endLocation"]);
            },
            error: function (xhr, status, error) {
                console.log(xhr)
            }
        });
    }

    $("#UpdateButton").click(function (e) {
        let params = (new URL(document.location)).searchParams;
        let id = params.get("id");

        $.ajax({
            url: "http://localhost:8888/api/Reservation/" + id,
            type: "patch",
            contentType: "application/json",
            data: JSON.stringify([
                {
                    op: "replace",
                    path: "Name",
                    value: $("#Name").val()
                },
                {
                    op: "replace",
                    path: "StartLocation",
                    value: $("#StartLocation").val()
                }
            ]),
            success: function (result, status, xhr) {
                window.location.href = "AllReservation.html";
            },
            error: function (xhr, status, error) {
                console.log(xhr)
            }
        });
    });
});
Understanding the Update Reservation code

The reservation id is sent to this page’s URL in query string. So the GetReservation() gets this id and fetches it’s data by making the API call.

The HTTP PATCH type of request is made by the UpdateButton() click’s code which is:

$("#UpdateButton").click(function (e) {
    let params = (new URL(document.location)).searchParams;
    let id = params.get("id");

    $.ajax({
        url: "http://localhost:8888/api/Reservation/" + id,
        type: "patch",
        contentType: "application/json",
        data: JSON.stringify([
            {
                op: "replace",
                path: "Name",
                value: $("#Name").val()
            },
            {
                op: "replace",
                path: "StartLocation",
                value: $("#StartLocation").val()
            }
        ]),
        success: function (result, status, xhr) {
            window.location.href = "AllReservation.html";
        },
        error: function (xhr, status, error) {
            console.log(xhr)
        }
    });
});
Notice that I used the JSON.stringify() method to send the updated data for the reservation to the API:
data: JSON.stringify([
    {
        op: "replace",
        path: "Name",
        value: $("#Name").val()
    },
    {
        op: "replace",
        path: "StartLocation",
        value: $("#StartLocation").val()
    }
])
Test the functionality
Go to ‘AllReservation.html’ page and change the URL for the edit icon to UpdateReservationPatch.html.
appendElement.append($("<td>").html("<a href=\"UpdateReservationPatch.html?id=" + value["id"] + "\"><img src=\"icon/edit.png\" /></a>"

Then check the functionality which is shown by the below video:

Update Reservation Patch

Get a Reservation by it’s Id

Here I will have to invoke the following API method:

[HttpGet("{id}")]
public Reservation Get(int id) => repository[id];
Create a new HTML Page called GetReservation.html and add the following code to it:
<div class="form-group">
    <label for="id">Id:</label>
    <input type="text" class="form-control" id="Id" />
</div>
<div class="text-center panel-body">
    <button id="GetButton" class="btn btn-sm btn-primary">Get Reservation</button>
</div>

<div id="resultDiv" style="display:none">
    <h2>Reservation</h2>
    <table class="table table-sm table-striped table-bordered m-2">
        <thead><tr><th>ID</th><th>Name</th><th>Start Location</th><th>End Location</th></tr></thead>
        <tbody></tbody>
    </table>
</div>

There is an input control where user will enter the reservation id and a button which on clicking will fetch the ‘id’s’ data from the API.

There is also a table element which will show the fetched data of the reservation.

Next, add the following jQuery code to this page:

$(document).ready(function () {
    $("#GetButton").click(function (e) {
        $("table tbody").html("");
        $.ajax({
            url: "http://localhost:8888/api/Reservation/" + $("#Id").val(),
            type: "get",
            contentType: "application/json",
            success: function (result, status, xhr) {
                $("#resultDiv").show();
                if (typeof result !== 'undefined') {
                    var str = "<tr><td>" + result["id"] + "</td><td>" + result["name"] + "</td><td>" + result["startLocation"] + "</td><td>" + result[
                    $("table tbody").append(str);
                }
                else
                    $("table tbody").append("<td colspan=\"4\">No Reservation</td>");
            },
            error: function (xhr, status, error) {
                console.log(xhr)
            }
        });
    });
});

Important thing to note is the id value which is added to the URL of the API:

url: "http://localhost:8888/api/Reservation/" + $("#Id").val()

Once I received the value from the API I then show it inside the HTML table. Check the code inside the success callback method which does this work.

Test the functionality

Open the page in the browser and enter 2 in the text box and click the button. You will soon get the reservation data for the 2nd reservation object.

Check the below video:

Get a Reservation by id

Upload Image to the API

Here I will have to invoke the following API method:

[HttpPost("UploadFile")]
public async Task<string> UploadFile([FromForm] IFormFile file)
{
//…
}
Start by creating an HTML page called AddFile.html. Add the following html to it:
<p>
    <a href="AllReservation.html" class="btn btn-sm btn-primary">Back</a>
</p>
<input type="file" id="File" />
<div class="text-center panel-body">
    <button id="AddButton" type="submit" class="btn btn-sm btn-primary">Add</button>
</div>

<div id="fileDiv" style="display:none">
    <h2>Uploaded File</h2>
    <img id="fileImg" />
</div>

There is an input element of type file that will be used to upload an image to the API. Once the file is uploaded I will show it inside the img tag.

Next, add the following jQuery code to this page:

$(document).ready(function () {
    $("#AddButton").click(function (e) {
        data = new FormData();
        data.append("file", $("#File")[0].files[0]);

        $.ajax({
            url: "http://localhost:8888/api/Reservation/UploadFile",
            type: "post",
            data: data,
            processData: false,
            contentType: false,
            success: function (result, status, xhr) {
                $("#fileImg").attr("src", result);
                $("#fileDiv").show();
            },
            error: function (xhr, status, error) {
                console.log(xhr)
            }
        });
    });
});

The file is added to the FormData object like:

data = new FormData();
data.append("file", $("#File")[0].files[0]);

And then I make the HTTP POST type of request to the URL – ‘http://localhost:8888/api/Reservation/UploadFile’.

Once the image is uploaded to the API server, I show it inside the img tag. I do this inside the success callback method:

success: function (result, status, xhr) {
    $("#fileImg").attr("src", result);
}
Test the functionality
Open the page in the browser and upload an image to the API just like what is shown by the video:
upload image

The link to download the full source code of this tutorial is given below:

Download
Conclusion
This API tutorial gives you all the working knowledge of consuming any API with jQuery. Download the source codes and use it freely in your website. Do check my other jQuery tutorials to.
Next: Learn how to Consume an API in ASP.NET Core using C#

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.

Leave a Reply

Your email address will not be published. Required fields are marked *