Introduction to the Asynchronous JavaScript + XML

Overview

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:

An HTTP Request

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:

@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript">
    var app = angular.module("appExercise", []);

    app.controller("ExerciseController", function () {
        var xhrService = new XMLHttpRequest();
    });
</script>

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:

@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript">
    var app = angular.module("appExercise", []);

    app.controller("ExerciseController", function () {
        var xhrService = new XMLHttpRequest();

        xhrService.send();
    });
</script>

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:

XMLHttpRequest.open(method, url, async = true, user = null, password = null);

The first argument is the type of method used on forms (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:

@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript">
    var app = angular.module("appExercise", []);

    app.controller("ExerciseController", function () {
        var xhrService = new XMLHttpRequest();

		xhrService.open("POST", "~/App_Data/Service.txt");

		xhrService.send();
    });
</script>

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:

@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript">
    var app = angular.module("appExercise", []);

    app.controller("ExerciseController", function () {
        var xhrService = new XMLHttpRequest();

		xhrService.onreadystatechange = function () {
        
		}
    
		xhrService.open("GET", "Service.txt", true);
		xhrService.send();
    });
</script>

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:

@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript">
    var app = angular.module("appExercise", []);

    app.controller("ExerciseController", function () {
        var xhrService = new XMLHttpRequest();

			xhrService.onreadystatechange = function () {
    		if (xhrService.readyState == 4) {
	        	. . .
		    }
    		else
        		alert("The document is not ready");
		    };

			xhrService.open("GET", "Service.txt", true);
			xhrService.send();
    });
</script>
Or you can qualify the member using the name of the class. Here is an example:
@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript">
    var app = angular.module("appExercise", []);

    app.controller("ExerciseController", function () {
        var xhrService = new XMLHttpRequest();

			xhrService.onreadystatechange = function () {
    			if (xhrService.readyState == XMLHttpRequest.DONE) {
	        	. . .
	    	}
		    else
        		alert("The document is not ready");
		};

		xhrService.open("GET", "Service.txt", true);
		xhrService.send();
    });
</script>
UNSENT 0 The request has been created but it has not (yet) been sent
OPENED 1 The XMLHttpRequest.open() method has been called
HEADERS_RECEIVED 2 The XMLHttpRequest.send() method has been called
LOADING 3 The requested document is currently being downloaded

Because the status of the document can also be an issue, you can use a Boolean conjunction to also check the HTTP Status Code of the document. Here is an example:

@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript">
    var app = angular.module("appExercise", []);

    app.controller("ExerciseController", function () {
        var xhrService = new XMLHttpRequest();

		xhrService.onreadystatechange = function () {
		    if( (xhrService.readyState == XMLHttpRequest.DONE) && (xhrService.status == 200) ) {
        		. . .
	    }
	    // else
	    //     alert("Something went wrong");
	};

	xhrService.open("GET", "Service.txt", true);
	xhrService.send();
    });
</script>

Introduction to Accessing an Ajax Document

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:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise: Service</title>
</head>
<body>
<script type="text/javascript">
    (function showMessage() {
        var xhrService = new XMLHttpRequest();

        xhrService.onreadystatechange = function () {
            if (xhrService.readyState == XMLHttpRequest.DONE && xhrService.status == 200) {
                document.write(xhrService.responseText);
            }
        };
        xhrService.open("GET", "Service.txt", true);
        xhrService.send();
    })();
</script>
</body>
</html>

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

When creating a Web project, you can use XML to create, manage, and maintain data for your website. As you may know already, XML offers a complete database solution.

Both the JavaScript language and its many libraries, which include 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.


Previous Copyright © 2018-2019, FunctionX Next