API calls using jQuery
jQuery was one of the first and most important libraries written for developers in JavaScript. When web development started to attract more developers and the WEB 2.0 era started there was the problem of supporting multiple browsers. jQuery was meant to be the Swiss Army Knife for web developers. It provided (and still does) a unified wrapper above the different implementations of functionalities in the browsers. Today there are many JavaScript libraries which are built on top of jQuery, like KendoUI, Bootstrap, Backbone.js and many others.
AJAX
AJAX (Asynchronous JAvaScript and XML) was introduced in the early 1990’s, it is a web developing technique which helps data communication between client and server. I am using the WEB API service from the [RESTful Web Services using ASP.NET WEB API] article to demonstrate how to make AJAX GET and POST requests. The code loads the contacts from a service and received JSON response:
$.ajax({
url: "/api/contacts",
type: 'GET',
dataType: 'json'
}).done(
createContactList
).fail(function (error) {
console.log(error);
alert("Error occurred while loading contacts!");
});
Using the $.ajax() method an async request is sent to the /api/contacts URL. The type of the request is set to GET and the expected dataType is set to json. The method returns a promise and done() and fail() methods can be chained to the execution. Using Promises (and Deferred Objects) we can register multiple callback methods for an async operation. The done() method will be invoked if the code in the promise executes successfully, in case of errors the fail() method is invoked.
Because accessing services that return json
data became very common, jQuery developers added the getJSON()
method:
var dataToServer = {};
$.getJSON("/api/contacts", dataToServer, function (data, status, jqXHR) {
console.log(status);
createContactList(data);
});
Using this method is much easier than $.ajax(), it takes the URL where the data is loaded from, in case there needs to be sent a filter to the server and this can be sent as a second parameter (dataToServer variable).
dataToServer.id = "4093e51f-95cb-4a3a-8572-cd4c19321fb8";
$.getJSON("/api/contacts", dataToServer, function (data, status, jqXHR) {
console.log(status);
console.log(data);
});
The result can be seen in Google Chrome’s Developer Tools (in case you are using Firefox, then Firebug is what you are looking for):
The third parameter of the getJSON()
method is a function which handles the response. The first argument is the data in json
format, the second argument is the HTTP status of the response and the third parameter is the XMLHTTPRequest
object.
Using $.post()
we can make HTTP POST requests to an API, send the data as JSON and define the response handler function as we did before:
$.post("/api/contacts", {
FirstName: "Advanced",
LastName: "jQuery",
Email: "aj@example.com",
Website: "http://example.com"
}, function (data, status, jqXHR) {
console.log(status);
console.log(data);
});
The second parameter should contain the json
data which needs to be sent in the POST request.
DOM Manipulation
Now let’s check the createContactList()
function. The role of this function is to create an ordered list with all the names (first name and last name) and ids of the contacts returned by the api. It receives a data parameter which is an array of json
objects.
function createContactList(data) {
var container = $('#contacts');
var list = $("<ol></ol>");
$.each(data, function (idx, item) {
var name = item.FirstName + " " + item.LastName + " [" + item.ID + "]";
console.log(name);
var newEntry = $("<li></li>");
$(newEntry).text(name);
$(list).append(newEntry);
});
$(container).append(list);
}
First I look up the container, using jQuery selector (looking for html element with id=”contacts”
). After that I create a new ordered list, I will append the items with first name, last name and id to this list later.
The $.each()
is a useful iterator function, the biggest advantage it has is that you get the both the index and the item from the processed collection. It is a combination of for and foreach language constructs from other languages. For each object in the data collection it invokes the function passed in as parameter. In the anonymous function I create the concatenated string of FirstName
, LastName
and ID
fields and log the value to the console.
Then, I create a new list item (newEntry), using the text()
method I set the text value of the li
HTML element. At the last line of the function I add the newEntry to the ordered list. When the $.each()
ends the execution I append the list to the container items using the append()
method.
As you can see jQuery is a very powerful library for DOM manipulation and client-server communication. It supports adding plugins and through the years there were created thousands of jQuery plugins, starting from data grids to color pickers, text editors and other UI controls.
The sample codes can be found on GitHub, under Views/Home/AdvancedjQuery.cshtml.