Monday, June 11, 2007

Two styles of Ajax

Introduction

Ajax started quietly materet technology, and it has already processed Patterns different approaches, schools (and there are mandatory and holy war). In particular, several people have (for example note Frank Sommers, which spodvigla me to write this), I read that shaped two fundamentally different approaches to writing ajax-prilozheny :


* A ready HTML on the server automatically implement it in the right place pages
* transfer to the only structured data, and change them HTML'a script on the client


Though Frank says that the two approaches are incompatible, I discovered that it was their very confusing, and I think that good :-).




More approaches

Sending HTML
The approach to the transfer HTML'a ideal for pages which, in conjunction with the server change slightly. For example some form, which after sabmita server again appears on the screen, and with it, or paints a picture that all is well or painted list of mistakes. The ajax reduces the amount of data transmitted on the network server is not taking any form of display, and only the assay.
The undoubted advantages of this approach include exceptional ease of ideas from which directly follows that on the client side can automate virtually all :


* substitution sabmita forms processor javascript'ovym
* formation of the scripting processor data in a form suitable for sabmita server (name1 = value1 & name2 = value2)
* receive an answer and introducing it into the page


Virtually all that remains to be done programmer is :


* tknut finger in it is what button he wants "to make ajax" and what block from the then save the result
* Server explain SWT, which is part of the answer must be cut to requests ajax'nyh


The cons approach, I would include that it is worse than working for "vysokodinamicheskih" page, where one of the changed parts. For example a long thread of comments where sabmitu form with the server to be replaced with a new commentary and, perhaps refresh line "N comment, which is quite a different page. Here, in the automatic model, you should refer to the part, which includes all the necessary pieces, even if there are data that are not expected to change. In practice, this may mean that the network running nemalenkie amounts of data comparable to the size of the actual page, and the whole purpose ajax'a comes down to lack animation browser icon in the upper right-hand corner.
And I underline "may", unfortunately, is true more often than I would like to, because this fully automated approach attracts many developers who do not have the time and / or willingness to deal with scripting, and rely on the fact that SWT help them do so small blood. They could never say on time or properly correct the problem at a lower level.




Transfer structural data

The transfer of structured data was essentially ajax'a even when he called the XmlHttpRequest. So it is a creation designed to appeal to the server and receive a description of the status of the system, expressed in XML, a language that is convenient for computer processing. Immediately I say that despite the fact that this was intended, a light wedge at XML-otvetah not Tsiolkovsky, and the structure can be made differently, as a little later.
Plus, this approach to maximize flexibility. You can make absolutely any format and dataset, which was requested from the server, which is exactly the type of information that is not enough for the customer, and nothing more. At the same customer through Javascript'a page can be changed completely, and as you see fit.
Take the same example with commentary : commentary sent to the server, and the response back like this : What does that comment has been validated and are now on page 12. Everything else can do for you : pririsovat new unit commentary, there perekopirovat text moulds, fomochku delete, update of the new figures.
The most obvious disadvantage of the transfer is much greater volume and complexity of programming. And it is several things.
The first difficulty is to use XML'a. Although the format of a clear and remarkable, in Javascript'e it can be operated only through DOM. That unable to write and very hard to read : too much text for simple things. Fortunately, this particular flaw in the recent move by JSON format : the data returned from the server in the form of XML, but as a piece of code creates Javascript'ovogo object with your structure : He immediately eval'om performed in the script and you get a response facility, which has response.status and response.quantity. It is very easy and without

The emotions of random XML-otveta remains the second issue : a full HTML manually DOM-metodam that, again, and difficult to raise.
Even worse, that most of these are two very different places, which is defined as pages : HTML-shablon and Javascript'ovy code. That means changes to accurately duplicate here and there. And it means that for writing HTML'a you now need a person who can write and HTML, Javascript and heavy. "Maintenance hell, in other words.
In fact, when I began with XmlHttpRequest'om played, it seemed very natural to me : every trick able parsit XML, then this is the correct way to use. The result of the exercises was fairly songs custom ajax-interfeys to chat with many without fenechek. Then, in 2003, he was terribly technologically advanced, but drilling it into something known, we never spodobilis. I was surprised even now that he is still working. Now here is the link to the history :-)




Combining the best features

The incompatibility, which said Frank Sommers, present only in terms of programming, which selects the transfer HTML, and does not want to be immersed in scripting at all. However, if the programmer is not opposed to this in principle, the transfer of the structure can be combined with the transfer HTML'a. The principle, in fact, it is very simple :


* response from the server goes to JSON-obekta
* things, not to generate HTML (eg move something somewhere, hide / open, etc.), performed by the script, using the data from the facility
* if you want to change something trivial pieces of HTML, they passed rows in the same facility and which must be inserted
* Variable part of HTML on the server are formed as small shablonchiki included, and used to start a page and ajax-otvetah


In other words, all the "great idea" is that the need to abandon dogma "Only XML'om" and enjoy what is convenient.
The only thing that I have not liked this approach is that on the server side, the work of a few. Without ajax'a code, which serves as POST form, is only two answers - either the same form with errors, or redirecting, when all is well, since ajax'om to each response option is added to the issuance JSON-objects.

Using AJAX in ASP.NET technology through Atlas.


AJAX (Asynchronous JavaScript and XML) is a cross platform technology publish. This technology allows developers to perform asynchronous requests to the Web, using the markup language of XML.
Technology firms Microsoft code-named "Atlas" enables the use AJAX to create server applications based on ASP.NET 2.0 technology.
This article focuses on a simple Web-based applications to dynamically on the client side complete data pull-down list and make dynamic loading additional information from the database using ASP.NET 2.0, AJAX and Atlas.
To begin with the Atlas technology to download an extension to Visual Studio 2005. You can do this with the Microsoft site (download).
With this expansion should create a new Web project using the template "ASP.NET 'Atlas' Web Site" (Fig. 1)


Fig. one window for a new project based on the template



Fig. 2 Sozdavaemaya table sprEmployee

After setting up a database and fill it Which of you are ready to create web necessary to extract information from the database in XML format.
To create a web in the window, select "Solution" Exploler up project, and then to me Website select Add New Item. In the dialog box (Figure 3) choose a template Web Service, a name WebAccess.asmx and remove tick Place code in separate file.


Fig. 3 window of a new web

Now add code to our web : Code Listing 1 Source Code Web

Now proceed to a web page to access information on the accounts. To that end, providing the box "Solution" Exploler up in the draft and selecting a menu item Website Add New Item, ask relevant parameters created a page (Figure 4). :
Template-Web Form.
Name-AtlasDropDown.aspx.
Similarly Place code in separate file-removed.


Fig. 4 Create a new web page

After creating a web introduce a code necessary for the work. Code Listing 2 source code web

Now start up project implementation. If all goes well, you should show that the browser window (Figure 5), and after downloading the list and select a record you will about this type as in Fig.

AJAX - A New Approach to Design

Home

If both can be called "glamurnym" something in the contemporary design of interfaces, it is a web. After all, the last time you heard that someone admired interface is not available on the Internet? (Ok, except iPod.) All the latest and innovative work on the Web.
However, the web developers can not do anything to envy from their peers, which desktop-prilozheniya. You have all the strength and speed of response, which seem inaccessible to the web. The same simplicity, which resulted in the rapid spread of a global network now a gap between the user interface, which we can provide, and interaction with the user desktop applications.
The gap is closing. Take a look at Google Suggest. Look, the alleged proposal almost continuously updated as you enter text. Now go to Google Maps. Increase scale. Capture the cursor card and its Moving back and forth. Again, everything happens almost instantly, without waiting reloading the page. Google Suggest and Google Maps are two examples of a new approach to web design, which we call the company Adaptive Path Ajax. It was established as a reduction of <Asynchronous JavaScript + XML> and represents a fundamental breakthrough in our ability on the web.


What is Ajax

Ajax is not a technology. In fact, the number of successful technologies in a decentralized manner, collected in a strong new direction. Ajax combines :

  • standardized presentation using XHTML and CSS;
  • dynamic display and interaction with Document Object Model;
  • sharing and management of data through XML and XSLT;
  • asynchronous data using XMLHttpRequest;
  • and JavaScript, which binds all of this together.
The classical model of Web applications is : most of the user sent back to the HTTP server. The server performs the necessary processing, receives, processes numbers, interacts with various legacy systems and then provides HTML page to the client. The model derived from the original application as a web of hypertext, but those who read the book know what makes web suitable for hypertext not necessarily make it good for software applications.


Figure 1 : Comparison of the traditional model web (left) with the model Ajax (right).

In this approach, many technical sense, but it is not good interaction with the user. The server does its work, which is the user? Correct, waiting. And with each user to step forward again and again.
Obviously, if we have created a web from scratch, it would not force the user to wait all the time. If the page is loaded, why should the user interaction with a halt every time program needs something from the server? Indeed, why do you see the app connects to the server?


What is the difference between Ajax

Annex Ajax preclude interaction type start-stop-start-stop by the introduction of Ajax as the intermediate layer between the user and the server. It may seem that adding a new level in the annex can only slow down the reaction, but actually the opposite.
Rather than download page at the beginning of the session custom browser downloads Ajax engine, written in JavaScript and usually concealed in a hidden frame. This engine is responsible for developing the user interface and interaction with the server on the user's behalf. Ajax engine allows interaction with the user asynchronously, that is, regardless of interaction with the server. So you no longer need to watch a blank browser window and cursor in the form of lost hours in anticipation of the server.


Figure 2 : Comparison of the traditional Web interaction diagrams (top) and asynchronous applications Ajax (bottom).

Each of the user, which usually produces HTTP now instead takes the form JavaScript-vyzova engine Ajax. Every response to the user who does not require treatment to the server, such as simple data validation, editing data in memory, and even some navigation, engine running independently. If the answer requires information from the server, such as loading additional interface code, data processing, or new data, the engine performs the necessary requests asynchronously, usually using XML, without interrupting user interaction with an application.


Who uses Ajax

Huge investments in the Ajax approach makes Google. All the major products announced last year Orkut, Gmail, the latest beta version of Google Groups, Google Suggest, and Google Maps - Ajax applications. (For technical details of Ajax read the excellent research Gmail, Google Suggest and Google Maps.) The rest remained behind : many favorite all properties service Flickr rely on Ajax and retrieval A9.com from Amazon use a similar technique.
These projects demonstrate that Ajax is not only in theory but also in practice for real applications. This is not ordinary laboratory theory. Applications Ajax can take any size from a simple and consists of a Google Suggest to a very complex and intricate Google Maps.
Working with Ajax last few months, we Adaptive Path realized that opened only the tip of the iceberg of the wealth of interaction and the speed of response, which provide applications Ajax. This is an important development web, and its importance will only grow. And given the large number of developers who already know how to use the technology, we expect to see a growing number of organizations will follow suit and use Google competitive benefits offered by the Ajax. What's next
The main task of building applications Ajax is not technical. Indeed, the underlying technology, the Ajax conditioned, stable and well understood. Rather, the challenge for developers of these applications is to forget about their perceptions of the restrictions web and start thinking more, a wide range of capacities.
It would be interesting.
Questions and answers.

March 13, 2005 : After the publication of essays Jesse we got a huge number of letters from readers with questions about Ajax. Here Jesse answer some of the most common questions.


Question. Is Ajax inventor company Adaptive Path, or did Google? Attended the company Adaptive Path in a Ajax-prilozheny Google?
Answer. Neither Google nor Adaptive Path is not inventing Ajax. Latest Google simply the best examples of applications Ajax. Adaptive Path was not involved in the development Ajax-prilozheny Google, but we did for its other customers.

Question. Is Adaptive Path sells components Ajax is the owner or registered trademark? Where they can be downloaded?
Answer. Ajax is not something that can be downloaded. This approach, a way of understanding of the architecture of Web using certain technology. Neither approach nor the name Ajax are not owned by Adaptive Path.

Question. Is Ajax another name for XMLHttpRequest?
Answer. None. XMLHttpRequest only part of the equation Ajax. XMLHttpRequest is the technical component that makes asynchronous interaction with the server; Ajax we call the general approach described in the article, which is based not only on XMLHttpRequest, but also the CSS, DOM, and other technologies.

Question. What does it give the whole name?
Answer. It was something more than a short <Asynchronous JavaScript + CSS + DOM + XMLHttpRequest> to discuss the approach with customers.

Question. How asynchronous interaction with the server has been available for many years. What is novel approach Ajax?
Answer. The novelty of using these outstanding way to change the basic model of interaction in the real web. Ajax provides only now because the time required for the development of these technologies and ideas about how best to apply them.

Question. Ajax is the technological platform, or just the style of design?
Answer. Both. Ajax is a collection of technologies used together in some way.

Question. For applications which type is best suited Ajax?
Answer. While we do not really know. Because of the relative novelty of this approach, our perception of where it is best applied is still in its infancy. Sometimes the traditional model is the best web solution to a problem.

Question. Does this mean that Adaptive Path anti-Flash this?
Answer. Just no. Macromedia is a customer of Adaptive Path, and we have long supported Flash-tehnologiyu. As specialists in Ajax, we expect that for some specific tasks that Ajax will be the most passing decisions, and sometimes the best solution would be Flash. Also, we are interested in exploring ways of combining these technologies (as in the case of Flickr, which uses both).

Question. Does Ajax restrictive access or compatibility with browsers? Do disable applications Ajax button <Back>? Is Ajax with REST? Are there views on security developments in Ajax? Can be developed Ajax-prilozheniya to work in the off JavaScript?
Answer. All these questions can only be answered <can be>. Many developers are already working in this regard. We believe that there is still hard to find any restrictions Ajax, and anticipate that the course will meet with the developer many such issues.

Question. Some of the examples you use Google XML altogether. Should I use XML and / or XSLT annex Ajax?
Answer. None. XML is one of the most advanced ways to input and output data from the client part of Ajax, but nothing prevents you achieve the same effects using such technology structure for the exchange as JavaScript Object Notation or the like.

Question. Simply Is An annex Ajax compared to the traditional Web?
Answer. Not necessarily. Ajax annex inevitably leads to the launch complex JavaScript code on the client side. Not so easy to do it that complex code efficient and free of errors, and to the success of this will require better design and development tools.

Question. Can annex Ajax is a better interaction with the user than traditional Web?
Answer. Not necessarily. Ajax more flexible interface designers. However, the more power we have, the more care is needed to treat it. We must be careful to use Ajax to enhance ease of use applications, rather than worsen it.

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.

AJAX application

Introduction

This AJAX two years ago was in Turkmenistan (and the word AJAX had not yet invented). The web-pages are updated on the fly, of course. On the contrary, without AJAX difficult to imagine some services.
It worked conventional web? Typically, the event (click on the link or by pressing a button) browser responds simply a request server. When the response came from the server, the contents page is updated.
One of the problems was that when you update the contents of a web page is transferred to the new state. The information on the previous state is only stored the data provided in the request. The more accurate information on the same condition of need, the more data must be sent in the request.
Another disadvantage is the need to send duplicate data sets client after each event. For example, if a user mistake when filling out the form, instead of short error is again loaded and form, and all information entered previously.
Modern browsers that support standards W3C DOM can bring web to a new level.
The interaction is almost the same. Here are just queries and receives a response from the server now script on the client side, but instead to update the page is updated, only part of it (instead of updating may be other options, for example, sent the following).
WebDAV distributed produced, and is part of the logic on the client side, and some server side. Such applications, and as the term "AJAX Applications (acronym stands for Asynchronous Javascript And Xml Applications).


XMLHTTPRequest object

For asynchronous requests from the client to the server-side browser is a special object called XMLHTTPRequest.
What methods and properties of the object that will be used beyond :

  • XMLHTTPRequest.open ( "method", "URL", async, "uname", "pswd"), a request to the server.

    • method, type of request, such as GET
    • URL - URL, for example http://localhost/file.xml
    • async - if True, it will be used asynchronous request, the implementation of the script will continue after the news. Otherwise, you would expect a response from the server freezing UI.
    • uname, pswd-ID and password for easy veb-avtorizatsii.

  • XMLHTTPRequest.send ( "content"), sends a request to a server. The content can be data for POST-zaprosa or an empty string.
  • XMLHTTPRequest.onreadystatechange-handler triggering events for each change of the facility. The facility may be as follows :

    • - 0 before the request has been sent (uninitialized)
    • 1-object initialized (loading)
    • 2-response from the server (loaded)
    • 3-connection active (interactive)
    • 4-completed facility (complete)

  • XMLHTTPRequest.responseText return from the server data as a string.
  • XMLHTTPRequest.responseXML if server response came in the form of a valid XML, returns XML DOM object.
  • XMLHTTPRequest.status return HTTP-otveta status as a number. For example, if the requested page 404 has been found on the server.
Consider the use of the facility by the simple AJAX-prilozheniya.


Paul SELECT finding

Suppose we have a table with a million records. The user must choose only one entry in the table (a relationship of "one to many"). Select the user is only one step in filling a large web.
Naturally, in order to enable the user to select an entry from a million, needed some means of finding this very account. For example, a simple text search by name.
In traditional web for this purpose would have to use a separate page and keep the rest in the form of a user session or break the process of filling forms at several stages. In AJAX-prilozhenii additional page is not required.
Select entries will be realized through two elements web. The first element is the text box where the user enters a keyword. It is sent to the server, and he returns only rows of tables that meet the search conditions. Server (a list) is placed in the SELECT, which the user and makes the final choice. Thus, when sending all forms server gets selected in the SELECT value in the form of ID records from a large table.
In HTML, it may look like this : In any event KeyUp (wheel button) in the text box link lookup ( 'text', 'id-selecta', 'url') As can be seen, at the beginning we get XMLHTTP-obekt using get_http (). The search text encoded in style and shape GET-zapros URL to the server. URL in this case would look something like this : http://localhost/cgi-bin/xmlhttp.cgi?text =...
The script on the server, receiving important text makes search in the table and sends a customer. In what events XMLHTTP object that the data received from the server and ready for use, fill link ( 'select_id', 'data'), which fill the SELECT list of scientific data.
The get_http () is the realization of kross-brauzernaya XMLHTTP object (in each browser, it produced its own). Its implementation comments you can easily find on the Internet, that is to say, an example of a textbook. The fill () gets to enter a value for the ID SELECT list to be filled, and the data retrieved from the server.
For simplicity, assume that the data from the server, we get a table, fields which are divided tab 't', a symbol of the line-transfer lines' n ':
id1tname1n
id2tname2n
... The contents of this table, we will complete the field SELECT OPTION elements. Done. Now for any web application, we can realize the importance of this choice multimillion list, which the user will be like a few keystroke. The network selection occurs almost instantly. In the case of unstable or slower connections to the server, it must also notify the user that the loading of data from the server is not yet complete. Worth and provide funds to respond to sever the connection.

Ajax DHTML

When opportunities become scarce, and improve already existing wall, and then a technological breakthrough. The breakthrough is AJAX (Asynchronous JavaScript and XML) approach to building Web user interfaces, so that the entire Web page does not have to be reloaded each time the user makes a change. AJAX is one of the components of DHTML.

What gives us the technology. The development WEB applications seeking to distinguish between client and server, and it comes from the widespread use of templates, such as Smarty and XSLT. The projects are becoming more complex and bind the different technologies become far too expensive for the developer. For example, all formatting styles are made in CSS or XSL files, HTML and XML data stored elsewhere, in the third handler server, database in the fourth. And if even 5-6 years ago almost everywhere could see the interlocking whole in a single file, it would become increasingly rare.

If a more complex projects there is a need for structure and readability of the code. Do not litter code programmer code Imposer and Imposer code-flattening designer, and so on.

The need to be distinguished work. For example, the designer will do its work, its operator, its developer, but no one interfere with each other will not. As a result, each project participant will know soon enough, those with whom he had to work. The group productivity and the quality of the project is more times. That problem has now been successfully resolved by the use of templates, but it also poses some difficulties, as to, say, connect Smarty, it is necessary to connect a software module templates, and clearly linked to the structure of the project. And this is not always possible and requires certain costs. Slightly easier to use XML + XSL bundles, as they provide more opportunities, but the alternative is more. And what if we look in the direction of something radically new that would combine all the best with the possibility that there? Try to JavaScript, which has the ability PHP or Perl, including working with graphics and database, which is much more convenient and practical scalability, and the same kross-platformen.

So what is AJAX? For the first time since moving to Ajax in February opened a year article Jesse James Garrett (Jesse James Garrett), "Rethinking the Web." Ajax is not independent technologies. This idea, which is based on two basic principles.

Using DHTML to the dynamic changes of this page.

Using the XMLHttpRequest to contact the server on the fly.

Using these two approaches to create a much more user-friendly WEB-interfeysy page, where interaction with the user. Using Ajax is the most popular after Google started to use it in their sites like Gmail, Google maps and Google suggest. The creation of these sites has confirmed the effectiveness of this approach.

So more : taking classical model WEB-prilozheniya :


Customers dial a search, address issues of his life, coming into contact with the server, it makes a request. The server performs the calculation in accordance with the request, calls to the database, and so on, after which the data are customers and, if necessary inserted in the templates and processed browser. The result is a page that we see, and that 80% of the population at the WEB called the Internet. This is a classic model, which has already proved himself and earned an honoured place in the sun. This is the simplest model of interaction and consequently the most common. But it is increasingly becoming insufficient. Imagine, on-line game "Ships", which played two hard-resident friend of South Africa and a resident of Japan. As with the model to make their game the most fun? In any case sunken ships will be stored on the server, and that would not verify whether the opponent looked like, need to be updated every time the page and podguschat outdated data. "But people come caching" - and you will say absolutely right, but more is not going to be. Caching only accelerate time interaction with the server, but does not eliminate the need to reload the page. Alternatively, you can put some time itself, but in this case the page will be completely reset.
Now look at the model of interaction AJAX :


The sequence of a client and it will likely not understand what would happen, and the word AJAX will be associated only with the name of the football club. But on the server side, all is not true.
When a server generated page, which will show you, and invite them to his interest sequenced. When informed (though not necessarily) a choice the client, its request will be treated to AJAX module, which will be of interest to all its computing and the server itself. But where is the innovation? The main difference in terms of this method enables us to dynamically access the server and perform actions interest us. For example, we need to appeal to the database and receive data of interest to us then we will use. The data we store in the XML file to be built dynamically, thus :
Create a new object of JavaScript : Then write function uses this facility Tel HTML file write a script that would : The file localhost / xml / checkUserName.php we are processing data from the command line in this case in your q. And by maintaining the structure of XML to store the same file. So we can receive and process data from a database, or something else we need. The server will process only the data that we need to be updated, not the entire page when you restart. Now back to the two friends, lovers sea battle : the emergence of this innovation, we can do the following : to check over every three seconds XML file, the test involves an audit of the database to a new record, that is, made of the opponent. If progress was made, page without rebooting mastering ships, thereby ruining the mood of water battles. This functionality is achieved using simple Javascript and stylesheets. This example is illustrative, but not limited to the use of this technology has much to the point. But it is not so easy. Let us now look at negatives. First, we can transmit data only method GET respectively large amounts of data to be left alone. Данная проблема уже не раз поднималась в разных источниках, но господа, есть ведь Сookies, которые вполне приемлемы в случаях передачи больших данных, чем может вместить в себя GET запрос, а Javascript в свою очередь имеет функции для работы с ними. The second-kross-brauzernost. XMLHttpRequest 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) : All modern browsers support this facility and problems arise only 1.8% of the users (according to data of the company SpyLog), which are very old versions of browsers that do not support this facility.
And finally, security. The shrink further. The main problem is that all the data and source code JavaScript functions can be seen by viewing the source code pages, respectively attacker can see the logic queries in a given set of circumstances necessary to implement a set of commands. This is not a role that we are mere comparison, but what to do in more complex situations, such as authentication, and then send passwords. As noted above, the assistance comes Cookies. The necessary data can be sent through them, just handle them. Take an example where the user will be authenticated using technology which is devoted to art.


Generating pages, we are creating unique values, which then placing variables in the server. And Cookies browser, and then when we get authorization username and password that we need to allocate processing module on the server.
Once the user data and clicked Submit his password entered into Cookies, and the user name is a reference open-http://www.mubestajax.com/ajax.php?login=pupkin example, when the data server in the first place a check of the data. Because the values that we have generated at the beginning of the server and then give them a global server variables and cookies must match, then verify the integrity of data transferred in the event of incompatibility program stops working. If all went well, then retrieved all the necessary data and the necessary calculations and work. This type of protection is fairly simple and effective. But for large projects, it did not come.
When a formulation of a security, better use of more sophisticated and reliable solutions. But in most cases, these precautions will be more than enough as the use of more complex modules using a technology that is not always part of the standard software of modern servers, the main feature of which is easy. This is the technology such as MySQL and PHP have become so prevalent because they provide easy work with its low resource consumption and little credibility. And to this software in the best possible approach to the above proposed.
In conclusion I would like to say that AJAX on the one hand, a huge leap in WEB engineering, but on the other hand this is a long standing stage of evolution, which opened new horizons in the field of software development. At the same time, this technology is still "cheese" because of its use at the moment rather pleasant exception. But I am sure that it is not yet time to hear everything.

Ajax - To begin

To begin ...

The pages of your site contains many specialized terms. When a user browses the site, it may raise questions regarding these terms. How do I get a visitor to a site where there are questions to delay answering questions? Previously, the terms of pages processed as a reference and the user can choose to click on them and get a window with contextual cues. This approach is quite awkward, it takes the user too much time to click on the link to await loading window, and then close the window. In an era of AJAX we can be closer to the wishes of users. We can make sure that when you have a mouse on the word immediately appear communication with the display and once with the mouse cursor extended term, the message disappeared. The presence of this service will not affect the volume of pages. When requesting contextual cues Java Script will apply to foreign vocabulary, receive and display its contents.

The method of obtaining information on the implicit request can be applied not only in the dictionary of terms. Foundation you look for the link with a double emphasis in such projects as hotscripts.com and devarticles.com? This contextual advertising based on the engine IntelliTXT company Vibrant Media. When you move your mouse over the link that appears in the window advertising the offer on the subject. This technology has already been dubbed in-text advertising.

Increasingly, the method applies to news portals. Visitors see on the front page of the portal only headlines. But when you move your mouse over the headline news they get their brief description. Thus, on the front page of the portal can accommodate as much more news. A visitor sees the headlines and the portal to get news announcements, it will be enough probezhatsya mouse cursor to the title.

Let us now look at how the contextual help is implemented using AJAX. Programmer, mastered this technique can be worked out to make news portal comment on the request or write module in-text advertising.

So, obviously we need to take care of the message ever, which will appear every time a visitor makes cursor to the term. To window appeared and disappeared overnight, it should be placed in hidden DIV. For a simple experiment, we can make it in the style of MS Windows system messages. The window should appear when the visitor checked your cursor over the term and disappear when the mouse cursor will be outside of the term. But at the moment the window should no longer gap, and the text of the definition of the term. Thus, we need to put the terms in the text and in inline tag, supporting events onMouseOver and onMouseOut. The first event should appoint the JavaScript, which would be the definition of the term, puts it in the window and displays a message box. The second event is to appoint a feature that simply leaving the message box. The parameter function, depicting window (getDefenition) Communications must identify the term. This term is used to query text of the definition by AJAX. Since your windows, we need his position under the mouse cursor to support Gecko-bazirovanyh browsers in this function should also be referred parameter event. The function to hide window (hideMessage) does not require any parameters. Now our task is to make the function call getDefinition JavaScript position reporting window. So, we have a window of communication, raportuyuschee of downloading data. Now, you request to the controller for the definition of the term. You can write your own functions for AJAX requests. But if you are just starting to work with AJAX, I suggest you ready library of Yahoo. The inquiry will be : If we ask controller, it is clear we have to write it. In general, this is the easiest part. The controller-back description of the term, according to POST. However language we use when writing controller, we simply follow a few simple operations. connect to a database with SQL query for the definition of a display on the console, as follows : This data structure, known as JSON. She perceived JavaScript explicitly, as <native>. If AJAX-biblioteki YAHOO response service next controller design We have only describe as showMessage (), which puts the text in the message box definition As you can imagine, to conceal the message will only change the attribute of When you try this example, it is unlikely that you will face problems with MS IE browser, but in FireFox you will find blinking the message. This is because FireFox unique event serves onMouseOver / onMouseOut. However, this problem can be overcome by placing flags delays in service functions of these events.

Scripts are given examples can be downloaded here.