When you work with client-side scripting, you will integrate AJAX with your jQuery code. AJAX and jQuery are not the same framework even though they both use JavaScript. AJAX stands for "Asynchronous JavaScript and XML." It's used to make calls to the web server without forcing the browser to refresh. The jQuery framework, however, is used to create client-side scripts and react to your user's input. The two frameworks are used in completely different ways, but they are often considered the same by new developers. In this article, we'll discuss AJAX and how it differs from jQuery.
AJAX Introduction
When you're designing your pages and aren't sure of what to use between jQuery and AJAX, remember that jQuery is mainly used to manipulate DOM elements. AJAX is to make asynchronous calls to the web server. If you aren't familiar with asynchronous calls, think of them as a way to make a call to a web server such as a form submission or a request from the database without forcing the browser to refresh. When you make a submission such as sending form data to a web server, the default behavior forces the user to wait for the data to submit and then a new page is shown in the browser.
You can use just about any API with AJAX. Just remember that AJAX works with XML but you can also convert this data to JSON. If you use any remote API, the documentation will tell you what output format it sends you. Both formats are widely used, so you can expect to work with both. Even if the documentation for an API doesn't give you examples in AJAX, chances are that you can still send calls to the API using API. The only two requirements for AJAX calls are that the format you send to the API is readable for the remote server, and the format sent back is data that you can parse.
To get started, let's look a basic AJAX sample.
<script>
function loadDoc() {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
document.getElementById("main").innerHTML = ajax.responseText;
}
};
ajax.open("GET", "testing.txt", true);
ajax.send();
}
</script>
The above code makes a call to the web server to request the file "testing.txt." However, before the actual file is opened, notice that we have a few statements that determine if the server sent the right responses.
The first statement initializes the XMLHttpRequest function and assigns it to the ajax variable. When you work with AJAX, this is a typical statement that you'll need in most of your AJAX code.
The second section of the code indicates if the web server is "ready," which is the value "4" sent by the server in the "readyState" property. The "status" property tells you the server response code. 200 means "OK" and is the standard response if the server request was processed successfully. Any other response would indicate that there was an error processing your request.
Of course, the text is not ready until the file is retrieved. The "open" method tells the AJAX procedure that you want to get a file named "testing.txt." Then, the "send" method sends the request to the server. Whatever text is in the file is shown in an HTML element with an ID of "main."
We placed the entire AJAX code in a function named "loadDoc." You must call the loadDoc function for this process to execute. If you try this with your own web pages, you'll notice that the page does not refresh and it's the process is practically invisible to the user. This is why developers use AJAX. It's more user friendly and speeds up load times for your users. Since performance and page speed increase user engagement, AJAX is a widely used technology for website developers.
Web Services And Data Formats
Web services is an older term used in the industry, but many APIs still have it engrained in their programming. Web services work with a few different formats, but the main ones are XML, SOAP, and HTML. We'll get into JSON in the following sections, but this section will focus on older formats that you'll still find on the Internet and using web services APIs.
XML is extended markup language, and it's actually the core to the SOAP format. XML was the original standard format used to send uniform data to a third-party application. You can make your own API and send data back in XML format, but JSON has taken over as the mainstream format. It still helps to understand the way XML is formatted to work with it. Since SOAP is a type of XML format, once you know standard XML you also primarily know SOAP.
Before you get into output format, you should first understand how to send data to a web service. The following AJAX code is the standard format for sending data to a web service.
$.ajax({
type: "post",
url: " http://webservicesite.com/service.asmx ",
contentType: "text/xml",
dataType: "xml",
data: xmldata,
success: SuccessFunction,
error: ErrorFunction
});
Notice that the URL has the "asmx" file extension. This is the standard web service extension for Windows development. The API developer will provide you with the URL for the web service page for any particular call that you make. For XML submissions, you must verify that you are using the XML data type. The "data" property is the data that you send to the server. In this example, it's assumed that you built an XML string contained in the variable "xmldata." Finally, if the call is a success, the "SuccessFunction" function is called. We haven't defined this function in our code, but you would create a standard JavaScript function to parse and display the returned data. If an error is returned, then the "ErrorFunction" function executes.
Once you have the posted data for the web service functioning, it's time to evaluate the different formats returned by a web service.
The following format is standard XML.
<?xml version="1.0"?>
<orders>
<order>
<customer>John Smith</customer>
<product>Red Widget</product>
<orderdate>7/22/2016</orderdate>
</order>
</orders>
XML looks similar to HTML except it only contains data used to parse and display to your users. XML uses opening and closing tags similar to HTML.
XML usually has a group that defines a list of records. In this sample, the data contains a list of orders. We only have one order, but these orders could be linked to one or more customers. Each order is within the opening and closing "order" tag.
With AJAX, you can parse through this data using node references. Each tag or element is considered a node. The following AJAX code is a basic snippet that gets the value of the first order node.
<script>
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("customer")[0];
var y = x.childNodes[0];
document.getElementById("main").innerHTML =
y.nodeValue;
</script>
This AJAX code gets all tags with the name "customer." We know that the customer tags (only one in this example) contain the name of the customer. Therefore, the result is that the customer's name displays in the "main" div container.
This is the standard XML format that is also used in SOAP. Most developers prefer standard XML, because SOAP is very verbose in its format. However, SOAP often offers more detailed responses than standard XML. The following SOAP example from Wikipedia.
POST /InStock HTTP/1.1
Host: www.example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: 299
SOAPAction: "http://www.w3.org/2003/05/soap-envelope"
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Header>
</soap:Header>
<soap:Body>
<m:GetStockPrice xmlns:m="http://www.example.org/stock/Surya">
<m:StockName>IBM</m:StockName>
</m:GetStockPrice>
</soap:Body>
</soap:Envelope>
The SOAP format is contained within an envelope. The envelope has a header and body similar to HTML. Within these containers are message details including the data returned. As you can see, it's similar to XML with some added details for each node.
The final return format is HTML. HTML isn't often used unless it has the right format that you need to display in your own pages. However, you could have an internal API that returns HTML that you can easily integrate into your existing HTML. Just remember that the HTML returned must be able to plug into your containers without rendering invalid HTML.
Since you already know what an HTML page looks like, you just need to know how to make a call to a web service and output the HTML to your web page. The following is an example AJAX call to a web service.
$.ajax({
type: "post",
url: "http://webservicesite.com/service.asmx",
contentType: "text/xml",
dataType: "xml",
data: xmldata,
success: function (data) {
$('#main').html(data)
},
error: function (data) {
$('#main').text("There was an error with your request.");
}
});
We used the same AJAX call that we had in the beginning of the section. We changed the success and error functions to custom ones that use jQuery to display the data. Because the data is HTML, we can just output it to the div container. We use a custom message if there is an error, so we use the jQuery "text" method to display an error message to the user. The error is based on the web service. If the web service returns an error, then the error function triggers.
Using AJAX with JSON
Although XML was the common standard years ago, it's widely been replaced with JSON. JSON is a much simpler way to represent your data. You can use JSON to return standard variables, arrays and objects. Several libraries and frameworks offer ways to parse JSON as well, so it's even much simpler to gain access to the data compared to years ago.
Just like XML, you first need to post data to a web service or API. The AJAX post function is used with JSON just like it's used with XML. You just need to specify the posted data format and parse through JSON instead of XML.
Let's first take a look at a simple JSON string.
{
"orderid": 22,
"customer": "John Smith",
"productordered": "Red Widget"
}
You'll notice that the JSON string is much simpler than XML, but it's also more difficult to read when it grows to a complex variable that contains several objects and arrays. This makes it difficult to identify if you have bad syntax in your string. The only way you'll know if the syntax is wrong is if your parsing class or library returns an error.
In the above example, the JSON object contains three fields that describe a customer order. This string can be contained in a text file, returned from a web service, or built after you query a database. However you build your JSON string, it must have the right format or a parsing error is returned.
Let's use the above string to send data to a web service using AJAX. The following code is an AJAX call to the same web service we used in the previous section.
var json = {
"orderid": 22,
"customer": "John Smith",
"productordered": "Red Widget"
};
$.ajax({
type: "POST",
url: "http://webservicesite.com/service.asmx",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#main').html(data.customer)
},
failure: function (data) {
$('#main').text("There was an error with your request.");
}
});
As you can see, the AJAX post is similar to the one we used in the previous section, but a few properties have changed. Instead of sending XML content to the web service, we send the JSON object we created. We assigned it to a JavaScript variable named "json." We set the contentType to JSON and then use a different format to retrieve the data. JSON is much easier to parse in native JavaScript libraries than XML. With JSON, you just reference the variable's properties by name instead of parsing node by node.
The "data.customer" variable retrieves the customer property returned by the web service. We're assuming the returned JSON string is the same as the variable that we send to the server, but you should read the documentation for the web service to verify the properties and data format that's returned to your website.
We use the same custom error message in the failure section of the AJAX post. Some APIs will send you a custom message should the call fail. Again, this would be something the API developer would indicate in the documentation.
The biggest mistakes developers make with AJAX calls is defining the wrong data format for either input or output and not accounting for possible errors that could be returned by the server. Remember that any response besides 200 means that the server returned an error code. This is when the "failure" function triggers.
Although AJAX is not the same technology as jQuery, you can integrate it with your jQuery code for asynchronous calls to the server that are then parsed and output on your page. When you work with web pages that make calls to external APIs, you will likely run into AJAX.