Asynchronous JavaScript And XML, which is AJAX or Ajax, is a set of techniques used to deal with data between a webpage and a webserver. Despite the presence of JavaScript in the name, Ajax is neither a language nor a library; it is a means of using JavaScript for Web requests. Despite the presence of "XML" in the name, AJAX techniques can be used to deal with any type of text-based file.

Although Ajax is not a language, the techniques it presents provide two valuable advantages:

You can send a request to a webserver without interfering with the user's work

The webserver can respond to your requests by sending data to a webpage but make changes only to the section that is concerned with the new or updated data. In other words, there is no need to refresh the whole webpage

Practical Learning: Introducing .NET Collection Classes

Start Microsoft Visual Studio

On the main menu, click File -> New -> Project ...

In the middle frame of the New Project dialog box, click ASP.NET Web Application (.NET Framework) and change the project Name to WaterDistribution1

Click OK

In the New ASP.NET Application dialog box, click the MVC icon and click OK

To support the various types of document requests to the server, the DOM provides a class named XMLHttpRequest. Once again, the presence of "XML" in the name doesn't mean a restriction on the types of files that can be made available. The XMLHttpRequest class is practically the central point of Ajax.

To let you create objects, the XMLHttpRequest class is equipped with a default constructor. As is the case for all non-static classes we have used so far, to get an XMLHttpRequest object, declare a variable and initialize it with this class using the new operator. Here is an example:

var xhrService = new XMLHttpRequest();

As is usually the case on the Internet, not all browsers support the XMLHttpRequest class or not all of them support it the same way. This means that, although most browsers support it, they may exhibit different behaviors, and sometimes the behaviors depend on the way the request is made.

Sending a Request

After formulating a request, when you are ready, you must send it to the webserver. To let you send the request, the XMLHttpRequest class is equipped with a method named send. Its syntax is:

send(body = Object);

This method takes an argument that is optional. The argument can be an object of type Document if you want the server to serialize the document before sending it. Here is an example of calling this method:

var xhrService = new XMLHttpRequest();
xhrService.send();

The Status of a Document

To respond to your request, the server must check the status of the document and act accordingly. To support this, the XMLHttpRequest class is equipped with a property named status. This is a standardized positive integer known as the HTTP Status Code. There are many code values available, they mean different things, and the server reacts differently depending on the status code. Some of the most common values are:

Value

Status

Description

200

OK

The request is/was successful. The value actually depends on the form method that was applied (POST, GET, PUT, or TRACE)

201

Created

The request was successful and a document was created

400

Bad Request

The webserver doesn't understand the request. This means that the request is probably badly formulated

401

Unauthorized

Although this response can mean anything or many things, the user probably didn't provide valid credentials (username and password) to access the document

403

Forbidden

Although this response can mean anything or many things, at first glance, the user is probably not allowed to access the document

404

Not Found

The webserver did not/cannot find the requested document, for any reason (maybe there is no such a document at all or you made a mistake in the name or path of the document, maybe the document was previously renamed or moved, etc). This is probably the most popular and the most concerned of all errors

408

Request Timeout

For any reason, it was taking the webserver too much time to fulfill the request or find the document. If this happens, the server is configured to stop (or postpone) searching and let you know

409

Conflict Timeout

For any reason, the webserver has concluded that this request conflicts with its work and therefore cannot be fulfilled

414

URI Too Long

Either the file name or the path is too long for the webserver to process, analyze, interpret, or understand it

Opening a Document

To let you specify the document you want to open, the XMLHttpRequest class is equipped with a method named open. The method takes two required arguments and three optional arguments. Its syntax is:

The first argument is the type of method we have used on forms in previous lessons. Use it in uppercase (POST, GET, PUT, DELETE, etc). The second argument is the name or the path of the file you want to open. Here is an example of calling this method:

The third argument is a Boolean value that specifies whether the operation should be performed asynchronously. The default value is true. The fourth and the fifth arguments are used if the user must provide credentials used to validate permissions to open the document. Their default values are null. If you don't have these values, don't pass them or pass each as null.

Getting Ready for an HTML Response

When you have made a request, the webserver responds one way or another. To let you prepare for a response, the XMLHttpRequest class is equipped with a read-only property named onreadystatechange. This property is of type EventHandler. The XMLHttpRequest.onreadystatechange property expects a callback function:

XMLHttpRequest.onreadystatechange = callback-function

To use this property, you can define a function and assign it to the property. This can be done as follows:

Or you can first define a function and then assign it to the XMLHttpRequest.onreadystatechange property.

The Current State of the Request

When the webserver receives a request to open a document, it wants to know the current status of the webpage as far as the operation is concerned. To support this status, the XMLHttpRequest class is equipped with a read-only property named readyState. The readyState property holds a value that is a static constant member of the same class. This means that the value is provided like those of an enumeration and the enumeration is named XMLHttpRequest. The members and values are:

Member

Value

Description

DONE

4

The operation is complete.

Use one of the values or members in a conditional statement formulated in the callback function to find out the state of the request. You can specify the value from its constant. Here is an example:

Ajax deals with any text-based document, including webpages, etc. To let you read the whole content of the document as one object, the XMLHttpRequest class is equipped with a read-only property named responseText, which is a string. If you want to display it in a webpage, you can pass it to a web control or pass it to a document.write() method. Here is an example:

If the document is XML, to let you open and analyze it, the XMLHttpRequest class is equipped with a read-only property named responseXML. This property produces a Document object:

Document responseXML;

The Document interface contains all of the methods and properties you can use to get the various nodes or elements in the document. You can then use XPath to find any node in the document.

Fundamentals of XML in Ajax

Introduction

When creating a Web project, you can use XML to create, manage, and maintain data for your website. As we saw in the revious lessons and we will see in this and the next lessons, XML offers a complete database solution.

If you have a background in Windows application programming (Win32, desktop solutions, C++, Delphi, Visual Basic, ASP.NET Web Forms, F#, Java, etc), you are probably familiar with controls events. ASP.NET MVC doesn't support events, at all (ASP.NET Web Forms supports a few events). As we saw in previous lessons, the only notification (notifications are the basis for events) you can send to a webserver is that one ore more values have been posted. With ASP.NET MVC, you can't even tell the webserver how (or why) the value(s) has (have) been posted. Since you can use only a Submit notification, any control that has a click (or change) event (a radio button, a check box, an HTML Submit button) can send that single notification but the webserver has not of identifying who (or what) sent that notification. You can write many lines of code to try to provide this information but the end result can still be unpredictable (in previous lessons, we were simply using an intermediary webpage to do a startup processing before getting to the actual webpage we needed).

Both the JavaScript language and its many libraries, which include jQuery and AngularJS, support events. Fortunately, you can use those libraries in your ASP.NET MVC project. You can use Ajax to open an XML file, read its content and use it in your ASP.NET MVC webpage. This allows you to use the JavaScript and/or jQuery events in the webpage.

Introduction to Ajax in jQuery

To support Ajax in jQuery, the $ namespace of the library includes a method named ajax. Therefore, to call this method, attach it to its namespace, as in $.ajax(). The method takes one required and many optional arguments. The first argument is an object that holds the information, called configuration, of how the Ajax operation will be carried. You can first define the object and then pass it as argument to the method. This can be done as follows:

Or you can define the object directly in the parentheses of the $.ajax() method. If you don't want to specify the whole object of the $.ajax(), the $ namespace provides various alternatives.

Primary Characteristics of Ajax in jQuery

The Method to Request Data

As seen in our early introductions, Ajax supports varius types of operations that include requesting, sending, editing, or deleting data. When formulating a request, you must indicate yor intentions to the webserver. To support this, the object of the $.ajax() method includes a property named type. Set the desired HTML method as the value of this property. The value is specified as a string. Here is an example:

To use XML in your Ajax operation, you have two primary options. If you want to use XML in memory, create XML code and include in a string. Declare a variable and assign the XML code to it. If your XML is in a file, to let you specify it, the object of the $.ajax() is equipped with a property named url. Set the name or path of the file to this property. Here is an example:

Again, Ajax supports various types of data, including text, HTML, etc. To let you specify the type(s) of the value(s) involved in the Ajax request, the object of the $.ajax() method is equipped with a property named dataType. Assign the type of value(s) involved in the Ajax operation. The values is specified as a string. Some of the available data types are text, html, and script. If you are using XML, specify the type as such. Here is an example:

When presenting an Ajax request to a webserver, the way you process the request depends on the method you chose, whether you are sending data to the webserver or getting data from it. To let you process the successful outcome of the request, the object of the $.ajax() method is equipped with a method named success. Create it as a property of that name. The value of the property must be a callback function. The method takes one argument which is an object that holds the data involved in the Ajax request. It can start as follows:

In the body of themethod, get the data from its argument. You can then use your knowledge of JavaScript and jQuery to get, check, validate, process, and perform any type of operation on the nodes of the XML object or file.

To execute the application, on the main menu, click Debug -> Start Without Debugging

In the Meter # text box, type 293-740

Click the Find button

Close the browser and return to your programming environment

A Shortcut to Get the Data

As a shortcut to perform an Ajax GET operation in jQuery, the $ namespace is equipped with a method named get. This method takes two arguments. The first argument is the name of the file and/or its path. The second argument is a callback function that will manage the request. The function takes as argument an object that holds the data of the transmission. Here is an example of calling this method:

The object of the $.ajax() method uses many more options than we reviewed above.

Processing a Request

Starting a Promising Request

The $.ajax() method works as a promise. As we saw in our introduction to promises in JavaScript, the $.ajax() method is a function that anticipates various outcomes, including a success, a failure, and an outcome that always occurs. The successful outcome is the place to process things that would go alright. The successful outcome is handled by a method named done. You can attach that method to the call of $.ajax(). The $.ajax().done() method takes a callback function as argument. That argument represents the data of the transmission. This can be formulated as follows:

To execute the application and test the Web controls, on the main menu, click Debug -> Start Without Debugging

In the Meter # text box, type 820-418

Press Enter

A Failing Promise

The failure outcome is used if you think that there is a possibility that the Ajax operation would not be honored. This outcome is handled by a method named fail. If used, attach this method to the done() call. The fail() method takes three arguments. The first is the HXMLHttpRequest object that carried the request. The second argument is the HTTP status code that specifies the failure and why it occurred. The third argument is the error that was produced.

To execute the application and test the Web controls, on the main menu, click Debug -> Start Without Debugging

In the Meter # text box, type 820-418

Press Enter

An Permanent Outcome

The last outcome is named always. Like its name suggests, this section is always executes regardless of what happens in the Ajax operation. The always outcome is created like a function. Attach it to the previous fail() call. The always() method takes two arguments which are the same of the first two arguments of the fail() method. As a result, to call all three methods, use the following formula: