Sunday, June 10, 2007

XMLHttpRequest object

First

One of the major difficulties faced by developers of web interfaces is that after the page has been in the browser client relationship browser to the server ends. Any element of the interface requires re-applying to the server to re-boot the new page. Because of the web loses its elegance and slow. In this article, I will discuss how this problem can be solved with JavaScript, and XMLHttpRequest object.
I am sure you know the traditional model of web interface. A user requests a page from the server, which is created on a server and then forwarded browser. We on this page have HTML-elementy describing the manner in which the user enters data. The user sends data to the server and obtains a new page based on the data entered, and the process is repeated. The whole process is determined by the nature of HTTP and different from how we work with conventional applications, which interface is inextricably linked to software logic.
Take a simple example entering the serial number in any Windows application. According to the rules, after you finish impose intricate set of numbers and letters in the fields adjacent to a green "check", meaning that you have entered the correct number. It appears instantly as a result of the logic of the "pad" in the interface. Once you have finished typing the number of its program and issue a response.
The Web is a standard of conduct is quite different. The fields in which you enter the serial number are exactly the same, but at the end of data entry, the user must click, send page on the server, which checks your information. Back User revert new page, which will appear on the right or the wrong serial number. User failing to return to the previous page and then try again. And so on ad infinitum.
Certainly not often web requires the user to enter a serial number, but there are countless other examples where rapid reaction of the user interface to be very welcome. And because the whole logic of the user, to obtain this result in the traditional web very difficult.


The scene appears JavaScript

Thanks to a number of JavaScript programming logic can be moved in HTML, allowing a quick response to user actions. However, this solution has one major drawback. The first problem is that as soon as JavaScript is in a user's browser with the page program logic is to see to the naked eye. If such verification enter e-mail addresses can not be scared, but when the check is linked with a serial number, checking algorithm is available to everyone who downloaded the page, which is not acceptable.
The second problem is that the major software logic in placing visit is not possible, because the interface simply is not designed to do so. The logic must be at the level of applications, rather than servers, and that means we again go back to the server. The problem is complemented by the fact that it is not always safe to expect the availability of JavaScript in the browser client. While most people leave JavaScript in their browsers included a large number of users who do not, or have the browser where JavaScript is unavailable or does not need as a class. Hence the logic that makes JavaScript on the client side, you still have to check on the server, just in case.


XMLHttpRequest

The solution can be XMLHttpRequest object. The site was first implemented by Microsoft in the form of ActiveX, but it is now available as a built object in all Mozilla and Safari. The site allows JavaScript-u built to the remote server without the need to reload the page. Indeed built sent and received full support for the "scenes" page, and you do not even notice.
This is a huge step forward, as it allows web developer to reach the same desired result of a fast user interface, while maintaining the software logic on the server. Through JavaScript-a data supplied by the user is sent to the server, where it is processed and the user almost immediately receive a response to your information.


Let's start with basics

Because of the conflicting stories XMLHttpRequest object is not part of a standard (though something similar has been proposed in the specification W3C DOM Level 3 Load and Save). So there are two different methods of the object to call the script code. In Internet Explorer ActiveX object is this : In Mozilla, and Safari it is easier (because there is an object embedded in JavaScript) : Of course because of this difference, you need a code branches, each of which will be carried out depending on which browser loaded script. There are several ways of doing so (including various saying khaki and the "conditional comment"). But I believe that the best just to check in the code, whether or not a browser facility. A good example is the code, taken from the Apple site, which released the documentation on the site. Let us, and we will enjoy : This code is particularly important to pay attention to onreadystatechange property. See how it is assumed to function processReqChange. This feature is Polo event, which starts whenever there was a change of the facility req. The designated numbers from 0 (object neinitsializirovan) to 4 (request is complete). It is because our script will not wait for a response from the server to continue their work. HTTP will be formed and sent to the server, but the script will be performed next. Because we have chosen the option of conduct, we can not just at the end of functions return the result set, as we know, we were at that time or not. For this we have provided processReqChange function, which will monitor the facility req, and tell us at the right time, the process of getting the document completed, and we can go further.
This function processReqChange want to check two things. One is waiting for the state of the object changes to req 4 (meaning that the process of obtaining documents from the server completed). Second, check HTTP-status response. You know that code means 404 "file not found" and 500 - "An error occurred on the server." But we need a good old code 200 ( "OK"), which means that our request on the server has been successfully concluded. If we received and the 4 and the code 200, we can continue with our script and process the results obtained from the server. Of course otherwise we must handle all errors, for example, if the response code is 200.


In practice,

I am going to create a model for a demonstration of the ideas. Many web is the procedure when a new user logs into the server and select "nickname" for the record. Very often the "nickname" is to be unique, because once there is a "book" on the server, a check on the database users, it is already a "nickname" or not. If you ever recorded on an email server, you remember how tedious search for "nickname", which has remained unused. It would be very good if carried out without the need to check each time to update the page.
To resolve, we will use the four key elements : XHTML-formoy, JavaScript functions, written specially for this situation, our two common functions, which we discussed above, and finally server script, which will go to the database.


Form

This is the easiest part of a simple form with a box for typing "book". By onblur events, we tied our script checks. In order to bring you a message of the test, I placed it in the shape and hid with CSS. This is a more elegant and polite way than standard dialog box function alert (). The CSS declared hidden properties of the class, and another class of error, which provides for the withdrawal of error messages.


Processing of data

The checkName used to verify data supplied by the user form. The function is to take the data, decide what the data server script give rise to another feature that will make all the "dirty" work with http and answers, and then process the answer. But our role will consist of two parts. One part is from the shape, and the other handles response from the server. I will explain why this is done, a little later. Answer-treated simply reply that we get from the server code will be either 1 or 0. 1 means that the "nickname" is already being used by someone. Depending on the response, our function is changing the name of class, the message is either running or hiding. As clear from the code, work on the server performs checkUserName.php script.


Building and HTTP response

As you saw above, the work done with HTTP two functions : loadXMLDoc and processReqChange. The first practically it is not necessary to change, while the latter requires some change to work with DOM-om. As you will recall, is the successful result of the request will not be referred to as processReqChange, we can not recover from this as a priority. Because of this, we need to implement a clear call to another location code to take advantage of the result. That is why checkName function is divided into two parts. Thus, the main task processReqChange function is to handle XML-otvet received from the server and to allocate some of that response functions checkName. We do not want to make this function a specific code, since these functions can be used and other elements of the page to access the server. Therefore, we are not inserted in the function name as processReqChange checkName. Instead, we decided that the server will be in its response to the title role, which it applied. Parsing The simple answer is no problem. Turning to the properties responseXML XMLHttpRequest object, we get XML-otvet that came from the server, which we will then proceed through DOM. Taking the name of the response function, which required a response, we know what functions must be transferred to the value. Once you have finished the test, remove the condition else that you did not bother users more than an error.


Server script

The last element of our puzzle is a server script, which will receive the request, process it and return the response in the form of XML. In our example, you would go to the database to determine whether this is "nickname" or not. For the sake of brevity, in my example, the script does not use a database, and just check the two names "Drew" and "Fred".
Of course, the same procedure must be checks and to the server script to be executed when the user clicks "Submit" on the registration form. This, in the event that he was disabled in your browser JavaScript, or you deliberately introduced "nickname", which is already in use. In addition to the busiest sites might be the case that in choosing "id", it was clear, but at the time it had already taken one.
As a next step by expanding the functionality of the script. For example the server may return alternative "sources" on the basis of "id", the selected user, but already employed.


Finally

This small example only slightly to the topic of XMLHttpRequest object. Here are some examples of its use : Google Suggest where XMLHttpRequest used to tell search terms, annex Ta-da Lists, which made data on the server via XMLHttpRequest again making the interface is very fast. The most interesting here is that the code work force, but to find any more interesting ways to use it.

No comments: