//

Thursday, August 27, 2020

Calling the server

 Introducing Ajax

Making calls to the server

Typically, when we make a call to the server, we need to refresh the entire page. Not only can this impact performance, it can change our user's perception of our pages. In addition, as developers, we'd like to be able to incorporate server-side resources into our pages, allowing us to update individual portions of the page with new data, rather than updating the entire page. This is where the XmlHttpRequest object comes into play and, Ajax.

Asynchronous JavaScript and XML (Ajax)

Ajax is a set of technologies that act together to make it easier for us as developers to make calls to server resources from JavaScript. Breaking down the three words that make up the acronym, you'll notice we have asynchronous (which jQuery simplifies through the use of promises), JavaScript (which we already know), and XML. XML is probably the one that doesn't fit, as XML is typically not a preferred mechanism for serialization. As we've seen, we typically want to use JSON, as its more compact and native to JavaScript.
Basic data retrieval

The most basic Ajax operation we can perform using jQuery is get. get contacts the URL we provide, and passes the string the server returns into the parameter we'll use for our event handler. get accepts multiple parameters, but the two you'll most commonly use are the URL you wish to call, and an event handler that will be executed on success.

$.get(
    'some-url', // The URL to call
    function(data) { // Success event handler
        // The data parameter contains the string
        $('#output').text(data);
    }
);


jQuery Ajax and promises

All jQuery Ajax calls return a jQuery promise. This means you can use done for your success event handler, and fail to catch any errors. The two code samples perform the same operations.

// Option one (pass the success function as a parameter)
$.get('some-url', function(data) { $('#output').text(data); });

// Option two (use the done function of the promise)
$.get('some-url').done(function(data) { $('#output').text(data); });
As we've discussed, JavaScript offers native support for serialization to and from JSON. jQuery builds on top of that, allowing you to easily retrieve JSON objects from the server by using getJSON.


getJSON

To retrieve a JSON object, you can use getJSON. getJSON accepts several parameters, but the most common two that you'll provide are the URL you need to call, and an event handler for success. Just as we discussed with get, getJSON returns a promise, meaning you can use done and fail as an alternative.

Because getJSON is expecting JSON data, it automatically deserializes the object, meaning you do not need to call JSON.parse.

If you were calling a server that was going to return a Person object, with properties of firstName and lastName, you could use the sample code below.


$.getJSON('/api/Demo', function (person) {
    $('#first-name').val(person.firstName);
    $('#last-name').val(person.lastName);
});

Making server calls

At this point, if you're new to making server calls through JavaScript or other technologies, you might have a few questions about how you're supposed to know where the data is, what URLs you should use, etc. The answer is, well, it depends.

Finding the right URL

Probably the most common question I get as an instructor is, "How do I know where to go find data?" Fortunately this is a much easier question to answer than it seems, and it's in the form of a question, "What do you want to do?"

When you're trying to discover services that you can call, approach it like you would a user. For example, if I asked you, "Where do you go to track a package shipment?", you would give me a couple of sites I could use. Or, if I asked, "Where do you go to find out sports scores?", you would give me a couple of different sites.

You start by determining what data you need, and then starting your investigation that way. When you find a service that offers the necessary data, they will provide documentation, containing the URLs you need to call to obtain specific types of data, what the data will look like, etc. They'll often provide a sandbox as well that you can use to practice and play.

Most commonly you'll be calling your own server and accessing your own organization's data. Then the answer becomes even easier: talk to the developer who created the server side code that you need to call. They can provide all of the information you need.

To get technical

When we start digging into making server calls, retrieving and uploading data, things can get a bit confusing pretty quickly. You may have some questions about how things work behind the scenes. Below you'll find some basic information about various standards and how to use them. However, a full discussion on REST and other APIs is beyond the scope of the course.
Verbs

As we discussed in the prior module, HTTP offers several "verbs", with the two most common being GET and POST. Those two names can cause some confusion, as they both have meanings in English. Get of course means to retrieve something, and post means to put something somewhere. Unfortunately, from a technical sense, that is not what GET and POST mean when they're related to HTTP.

GET and POST in HTTP terms are about how to send data to the server, not a determination of the server sending you data. The server will always send you data, be it a status code, string data, or a JSON object. GET and POST determine how we as the caller are going to send data to the server.

GET limits us to sending data in the URL only. Because the data can only be in the URL, we are not only restricted in the amount of data we're able to send, but in the data types. Large amounts of data cannot be sent in the URL.

POST on the other hand allows us to send data both in the URL, but also in what's known as the header. The header is information that's sent behind the scenes from the client to the server, and can be used to send almost any type of data, including binary data.

But, and I want to repeat this, both GET and POST return data. The difference between the two is how we're allowed to send data to the server.

HTTP and REST APIs

As we discussed above, if you want to access data on a particular service, and need to figure out how to send data, what URLs to use, what data you're able to send, and what data will be sent to you, you'll want to check the documentation provided by the service.

Needless to say, that can get a bit overwhelming, as anyone who is implementing a service can create their own API. Each API can be completely different than any other API that's been implemented. To try and provide some consistency, some standards have been set around HTTP calls.

The most common set of rules is in working with data. HTTP provides several verbs, including GET, POST, PUT and DELETE. Many servers perform specific operations behind the scenes based on the verb that you use. GET will retrieve objects, POST will create a new object, PUT will update an existing object, and DELETE will delete an object.

Building upon those common operations, the W3C has established a specification called REST. REST provides for various standards to provide even more consistency when making server calls.

The big thing to remember is nobody is obligated to follow any of these standards. You will find that most services will make good faith efforts to abide by the guidelines set forth by REST, but there may be differences in their implementations.


Posting data

If the service you're using follows standard REST practices, you'll notice that you can create a new object by calling POST. Or, if you're trying to upload a binary object, such as an image, you're forced to use POST, as GET won't allow that type of data to be uploaded.

post
jQuery's post funtion uploads the data you provide by using the HTTP POST verb. Like getJSON, it also passes the JSON object returned by the server into the parameter for the event handler. And, just like all of the Ajax calls we've seen, post also returns a promise.

Because jQuery is aware of the fact we're probably going to use JSON, you'll notice there is no need to call JSON.stringify or JSON.parse; jQuery handles that automatically for us.

// get the data we need to send
var person = { firstName: 'Christopher', lastName: 'Harrison' };

// Call POST

$.post('URL', // Pass in the URL you need to access
    person, // Pass in the data to send via POST
    function(data) {
        // success event handler
        // parameter contains value returned by server
    }
);
 

Ajax events

When making Ajax calls, you may need to update page content or change the availability of controls such as buttons when calls start or complete. jQuery Ajax offers several global events.

Start events

The two starting events are ajaxStart and ajaxSend. ajaxStart is raised when the first Ajax call is being made. ajaxSend is raised each time an Ajax call is made.

Completion events

jQuery Ajax offers two main events when each Ajax call is finished, ajaxSuccess, which is raised when a call succeeds, and ajaxError, which is raised when a call fails.
ajaxComplete is raised when each Ajax call completes, regardless of success or failure. ajaxStop is raised when all calls are completed.

$(document).ajaxSend(function () {
 // raised when a call starts
 $('#status').append('<div>Call started</div>');
}).ajaxComplete(function () {
 // raised when a call completes
 $('#status').append('<div>Call completed</div>');
});
 

Dynamically Loading Data 

Up until now, everything that we've seen has been about sending and retrieving objects, or basic strings. But what if we want to load HTML or JavaScript dynamically. Fortunately, jQuery provides those capabilities as well.  

Loading HTML

load will call the URL provided, obtain the HTML, and place it in the targeted item.
$('#target').load('some-url.html');

Loading and executing JavaScript

If you need to load a JavaScript file dynamically, you can use getScript. One important note about getScript is it downloads and executes the script when it's called.
$.getScript('some-url.js');

 

No comments:

Post a Comment

Effective Branching Strategies in Development Teams

Effective Branching Strategies in Development Teams Effective Branching Strategies in Developme...