How does ajax work? AJAX Basics for Beginners


Abbreviation AJAX(Asynchronous JavaScript and XML) symbolizes the concept of using a range of web programming technologies to enable update the contents of individual areas asynchronously HTML pages . Asynchronously means that updating the block you need HTML markup may occur asynchronously with updating the entire page. As a result, the browser will not experience the flickering that often accompanies a page refresh or the user moving to another page via a hyperlink.

Asynchronously can also mean parallel updating of several fragments at once. For example, when a page with a large number of tags is loaded , then the images themselves can appear gradually and parallel to each other. It is the ability to update not the entire Internet page, but a separate part of it, that makes AJAX technologies so popular and in demand in the field of web design. Quite often, AJAX is used in authorization scripts (capture generation) or when displaying the status of long-running operations performed on the server.

Without going into details, AJAX combines two main approaches to creating interactive Internet pages:

Using an object XMLHttpRequest to contact the server and receive a response from it in background via http protocol.

Dynamic updating of the page itself through its software interfaces object model (Document Object Model, DOM) in code. All together this is called .

What are the benefits of using AJAX? To understand this you need to use it and compare it with what happened without it. Below are a couple of undeniable ones. benefits of using AJAX when building Internet sites:

Reducing traffic and load on the server, since the server and client do not exchange the entire markup of the Internet page, but only part of it.

Better ergonomics and more high speed operation of the site's user interface.

Using AJAX has not only advantages, but also disadvantages that you have to put up with if you decide to use this software concept in your Internet projects. Here are some to keep in mind:

  • Data downloaded during background communication with the server through the XMLHttpRequest object is not included in the browsing history and cannot be added to browser bookmarks.

  • The content displayed as a result of an AJAX request may never be visible to search engines (Google, Yandex), since they do not imitate user behavior and do not execute JavaScript code.

  • Standard visitor counting and page viewing services may generate incorrect statistics.

  • Using not only AJAX software, but also any JavaScript scripts may result in your page behave differently under different browsers, and this behavior will not always be correct.
XMLHttpRequest object

Now I will briefly describe the scenario of how AJAX is used in its pure form, and then I will tell you in more detail how . As already mentioned, asynchronous calls to the server are made through the XMLHttpRequest object. First you need to create it, and this is done in different browsers differently. The procedure for creating an XMLHttpRequest that has a chance of working correctly everywhere looks something like this.

Function createRequest() ( var request = null; if (window.XMLHttpRequest) ( request = new XMLHttpRequest(); ) else if (window.ActiveXObject) ( try (request = new ActiveXObject("Msxml2.XMLHTTP");) catch ( ex) ( try ( request = new ActiveXObject("Microsoft.XMLHTTP");) catch (ex)(return null;) ) ) return request; )

//Create a request var request = createRequest() //Pass the http request type (GET or POST), request URL and mode: asynchronous request (true) //or synchronous (false), when the browser is suspended while the request is being executed. request.open("GET", url, true); //Defining the request completion handler request.onreadystatechange = onSuccess; //Execute the request request.send();

Where the function to handle the successful completion of the onSuccess request might look something like this:

Function onSuccess () ( try ( if (request.readyState == 4) ( //The request is completed if (request.status == 200) ( //and completed successfully //here we do something with the result of the request var result = request .responseText; ) else ( //here we handle unsuccessful request execution alert(request.statusText); ) ) ) catch(ex) () )

AJAX and jQuery

In principle, there is nothing complicated in the above example, but pay attention to the createRequest function. The ability of program code to work equally correctly under any browser is called cross-browser compatibility. To your program code became cross-browser you need to make serious efforts: you need to know the nuances of each browser and ways to resolve problems of incompatibility of its infrastructure with the ones you use software. Popular among web programmers Javascript library Not only does jQuery make working with the XMLHttpRequest object easier, it also ensures (and tries to) that your solution is cross-browser compatible. jQuery has several methods for working with AJAX technologies. First of all, this is the ajax method itself, which is the most universal and suitable for composing any requests to the server. The get and post methods internally also use the ajax method (they are its wrappers), and are intended, as you might guess from their name, to send to the server GET And POST requests accordingly. Below are JavaScript examples code for using AJAX using jQuery.

Function loadArticle_ajax(type, id) ( $..php", data: ((article_id:id)), success: OnComplete, error: OnFail )); ) function loadArticle_get(id) ( $..php", (article_id: id), OnComplete).fail(OnFail); ) function loadArticle_post(id) ( $..php", (article_id:id), OnComplete).fail(OnFail); ) function OnComplete(html) ( $("#content").html(html); ) function OnFail (response) ( $("#content").html("Error loading data:
"+response.statusText+"
" + response.responseText); )

The above functions perform a parameterized http request via a link (URL) of the following form:

Http://site/readarticle_content.php?article_id=id

The content retrieved depends on the id parameter. If in your case you do not need to pass any parameters, then leave the empty set () as the corresponding argument. You can look at the working example. That's all for me about AJAX and jQuery.

AJAX - What is it?

When existing opportunities become scarce, and there is no room to improve what exists, then a technological breakthrough occurs. Such a breakthrough is AJAX (Asynchronous JavaScript and XML) - an approach to building user interfaces web applications, in which the web page, without reloading, itself loads the data the user needs. AJAX is one of the components of the DHTML concept.

What does this technology give us? Currently WEB development applications tends to differentiate between the client and server parts, which is what determines the widespread use of templates such as Smarty and XSLT. Nowadays, projects are becoming more complex, and interweaving different technologies among themselves is becoming too expensive for the developer’s time. So, for example, all formatting styles are put into CSS or XSL files, HTML or XML data are stored in other sections, server processors in third sections, databases in fourth sections. And if 5-6 years ago almost everywhere you could see the intertwining of all this in one file, now this is increasingly becoming a rarity.

When developing more complex projects, there is a need for structured and readable code. You should not clutter the programmer's code with the layout designer's code, and the layout designer's code with the designer's edits, and so on.

There is a need to differentiate work. So, for example, a designer will do his job, a layout designer will do his job, a programmer will do his work, and no one will interfere with each other. As a result, each project participant will only need to know the data with which he will have to work. In this case, the productivity of the group and the quality of the project increases significantly. Currently, this problem is successfully solved by using templates, but this also creates certain difficulties, since in order, say, to connect Smarty, you need to connect software module template processing, and clearly linked to the project structure. But this is not always possible and requires certain costs. It's a little easier to use XML + XSL as they provide more functionality, but it's an alternative, nothing more. What if we look towards something radically new that would allow us to combine everything better, using the capabilities of what we have? Try to imagine JavaScript, which has all the capabilities of PHP or Perl, including graphics and databases, which has much more convenient extensibility and practicality, and is also cross-platform.

So what is AJAX? People first started talking about Ajax after the February 2005 article by Jesse James Garrett, “A New Approach to Web Applications.” Ajax is not a standalone technology. This is an idea that is based on two main principles.

Using DHTML to dynamically change page content.

Using XMLHttpRequest to contact the server on the fly.

Using these two approaches allows you to create much more convenient WEB user interfaces on those website pages where active user interaction is required. The use of Ajax became most popular after Google company began to actively use it when creating their sites, such as Gmail, Google maps and Google suggest. The creation of these sites confirmed the effectiveness of this approach.

So in more detail: if we take the classic WEB application model:

The client, typing the address of the resource he is interested in in the search bar, gets to the server and makes a request to it. The server performs calculations in accordance with the request, accesses the database, and so on, after which the received data goes to the client and, if necessary, is substituted into templates and processed by the browser. The result is the page that we see, and which 80% of the country's population located on the WEB call the Internet. This classic model, which has managed to prove itself and earn itself an honorable place in the sun. This is the most simple model interactions and, as a result, the most common. However, it is increasingly becoming insufficient. Imagine an on-line game "Battleship", which is played by two inveterate friends - a resident of South Africa and a resident of Japan. How can you use this model to make their game as enjoyable as possible? In any case, the data of sunk ships will be stored on the server, and in order to check whether the opponent has failed, it will be necessary to refresh the page every time and update outdated data. “But people invented caching,” you will say, and you will be absolutely right, but it won’t make it any easier. Caching will only speed up the time of interaction with the server, but will not eliminate the need to reload the page. Alternatively, you can set a certain self-refresh time, but in this case the page will be reloaded completely.

Now let's look at the AJAX interaction model:

The sequence of the client's actions is preserved and he most likely will not understand what will happen, and the word AJAX will be associated only with the name of the football club. But on the server side, everything looks different.

When accessing the server, a page is generated that will be displayed to the user and prompt him to perform a sequence of actions that interests him. With a conscious (although not necessarily) choice of the client, his request will contact the AJAX module, which will perform all the calculations he is interested in and work with the server as such. But what's new? The main difference is that this method gives us the opportunity to dynamically access the server and perform actions that interest us. For example, we need to access the database and get the data we are interested in, which we will then use. We will store the data in an XML file that will be generated dynamically, thus:

Create a new one JavaScript object:

Var req = new ActiveXObject("Microsoft.XMLHTTP"); (for IE) var req = new XMLHttpRequest(); (For everything else)

Then we write a function that uses this object

Var req; function loadXMLDoc(url) ( // branch for native XMLHttpRequest object if (window.XMLHttpRequest) ( req = new XMLHttpRequest(); req.onreadystatechange = processReqChange; req.open("GET", url, true); req.send( null); // branch for IE/Windows ActiveX version ) else if (window.ActiveXObject) ( req = new ActiveXObject("Microsoft.XMLHTTP"); if (req) ( req.onreadystatechange = processReqChange; req.open("GET ", url, true); req.send(); ) ) )

In the body of the HTML file we write a script that will:

Function checkName(input, response) ( if (response != "")( // Response mode message = document.getElementById("nameCheckFailed"); if (response == "1")( message.className = "error"; )else( message.className = "hidden"; ) )else( // Input mode url = "http://localhost/xml/checkUserName.php?q=" \\ + input; loadXMLDoc(url); ) )

In the file localhost/xml/checkUserName.php we process the data received from command line V in this case in the variable q. And we save the result in an XML structure, which we store in the same file. This way we can receive and process data obtained from the database, or anything else we need. In addition, the server will only process the data that we need to update, and not the entire page if it is reloaded.

Now let's go back to the two friends - lovers sea ​​battle: in view of the appearance of this innovation, we can do the following: check it every three seconds XML file this check implies checking the database for a new entry, that is, a move made by the opponent. If a move has been made, the page sinks ships without rebooting, thereby spoiling the mood of the participants in water battles. This functionality achieved by elementary using Javascript and style sheets. This example is quite clear, but far from complete; the application of this technology is much more significant.

However, not all so simple. Let's now look at the negative traits.

Firstly, we can only transfer data using the GET method, so large amounts of data will have to be left alone. This problem has been raised more than once in different sources, but gentlemen, there are cookies, which are quite acceptable in cases of transferring larger data than a GET request can accommodate, and Javascript, in turn, has functions for working with them.

The second problem is cross-browser compatibility. The XMLHttpRequest object is not yet part of any standard (although something similar has already been proposed in the W3C DOM Level 3 Load and Save specification). Therefore, there are two different methods for calling this object in script code. IN Internet Explorer The ActiveX object is called like this:

Var req = new ActiveXObject("Microsoft.XMLHTTP");

In Mozilla and Safari this is easier (since there it is an object built into JavaScript):

Var req = new XMLHttpRequest();

All modern browsers support this object and problems will arise only for 1.8% of users (according to statistics from SpyLog) who use very old versions of browsers that do not support this object.

And finally, security. Let's take a closer look at this. The main problem is that all data and source code of JavaScript functions can be seen by viewing the source code of the page; therefore, an attacker can trace the logic of request execution and, under certain circumstances, execute the set of commands he needs. This does not play a special role when we have a simple data comparison, but what to do in more complex situations, for example during authorization, and how to transfer passwords in this case. As mentioned above, Cookies come to the rescue. The necessary data can be sent using them, and they can also be processed. Let's take an example in which the user will be authenticated using the technology that the article is devoted to.

When generating a page, we generate unique values, which we then place in server variables. And in Browser cookies, then during authorization we receive the username and password, which we need to pass to the processing module on the server.

After the user has entered the data and pressed the Submit button, his password is entered into Cookies, and the user name is transmitted openly - with a link for example http://www.mubestajax.com/ajax.php?login=pupkin when receiving the data, the server first of all conducts reconciliation of the received data. Since the values ​​that we generated from the start of the server and then passed them to the global server variables and cookies must match, when checking the integrity of the transferred data, in case of a mismatch, the program stops working. If everything went well, then all the necessary data is extracted and the necessary calculations and work are carried out. This method of protection is quite simple and effective. But for big projects it won't fit.

When security comes to the fore, it is better to use more complex and reliable solutions. But in most cases, these precautions will be more than enough, since the use of more complex modules entails the use of technologies that are not always included in the standard software of modern servers, the main feature of which is simplicity. This is why technologies such as MySQL and PHP have become very widespread, because... they provide ease of operation with low resource consumption and sufficient reliability. And within the framework of this software it is impossible would be better suited the solution proposed above.

In conclusion, I would like to say that AJAX, on the one hand, is a huge leap in WEB engineering, but on the other hand, it is a long-overdue stage of evolution that has opened new horizons in the field of software development. At the same time, this technology is still quite “raw” since its use is limited to this moment rather a pleasant exception. But I am sure that everyone will hear about it more than once.

Last update: 11/1/2015

AJAX technology is a technology for asynchronous interaction with the server. Thanks to this technology, we can send requests to the server and receive responses from it without reloading the page in the background, and create rich interactive web applications, such as web chats.

Initially, the ability to asynchronously interact with the server was used in the form of an ActiveX object at Microsoft. Subsequently, the idea of ​​​​asynchronous interaction was picked up by other companies. And currently, the functionality of asynchronous requests in browsers is available to web developers through the XMLHttpRequest object.

Since this article is about jQuery, I won't go into detail about the XMLHttpRequest object. But I will briefly show the essence of its use.

So, first of all, to work with AJAX we need a web server. This could be Node.js, IIS, Apache, nginx. In the future I will use the Apache web server.

Let's create a web page where XMLHttpRequest will be used:

Load No news function ajaxload())( var xhr=new XMLHttpRequest(); xhr.onreadystatechange=function())( if(this.readyState==4)( if(this.status >=200 && xhr.status< 300){ document.getElementById("news").innerHTML=this.responseText; } } } xhr.open("GET", "ajax.php"); xhr.send(); }

In terms of markup, we have two elements: a button, when clicked, the ajaxload function is executed, and a div block into which data will be loaded when requested.

All our main action happens in the ajaxload function. First, we create an XMLHttpRequest object: var xhr=new XMLHttpRequest(); .

We will send requests through this object. When a response is received, the onreadystatechange event will fire. And to process this event, we assign the xhr.onreadystatechange property a response processing function.

In the processing function, we first look at the readiness of the response through the readyState property (the state this.readyState==4 means that the request is completed). Next, we check the response status code: if the server returned a status code between 200 and 300, then the request was successful.

And then we pass the response text to the div we have on the page via the responseText property.

In the line xhr.open("GET", "ajax.php"); we set the request method and the resource to which the request will go.

Well, with the last line xhr.send() we send the request. We ended up writing a lot of code to execute a simple request.

Let us have a request handler on our server for php language. I'll make it extremely simple. It will simply respond with html markup:

Now, when you click the button, an Ajax request will occur, the results of which will be loaded onto the page:

Now let's rewrite the page code from using jQuery:

Load No news $(function())( $("button").click(function())( $("#news").load("ajax.php"); )); ));

Thus, the code becomes cleaner and simpler by using jQuery libraries. We just need to use the load method, passing the resource address as a parameter. And the final result will be the same.

AJAX (Asynchronous JavaScript and XML) is a technology that provides dynamic requests to the server, during which there is no need to reload the page. The site functions an order of magnitude faster because the entire page does not need to be updated regularly, so its use becomes more convenient for the user, but not for search engines.

Great amount similar technologies began to be used back in the 90s of the last century. For example, in 1996 Internet browser Explorer 3 introduced the HTML IFRAME element, and two years later Microsoft implemented the Remote Scripting mechanism.

However, the term “Asynchronous JavaScript and XML” itself became known to the world only at the dawn of 2005, when Jesse Garrett released an article entitled “Ajax: a new approach to web applications”. In his material, Garrett described in detail how Internet applications are created for Google Maps and Gmail. He confidently stated that this was the beginning of a rapid development in the capabilities available to users in applications.

Jesse James Garrett

Jesse Garrett paid special attention to the AJAX technology, gave it a name and described the new trend in detail. But it is worth noting that he did not invent this technology, he only gave it a name.

After this, the field of Internet application development became much more advanced. From now on, users can see the results of data exchange between the browser and the server on their displays.

When you visit a certain website, you will immediately understand that it uses AJAX technology. Previously, users had to click on various buttons and follow the links to confirm your actions. Today, the web page independently accepts new data in real time without reloading on the user’s side.

All this ensures more convenient use of the web resource, since the time allocated for interaction with it is significantly reduced. Essentially, we begin to communicate with a high-speed application. And for it to work fully, you only need access to the Internet, as well as a browser that works with JavaScript.

How the technology works

To specifically understand how AJAX works, let's look at 4 critical steps:

  • The visitor accesses AJAX. As a rule, he does this through a certain button, which informs that when clicked you will get acquainted with additional information.
  • The system then sends the request and various data to the server. For example, you may need to download some file or information located in the database.
  • After receiving a response from the database, the server sends the data to the browser.
  • JavaScript receives the response and decrypts it into a user-readable form.
  • If we explain the essence of the technology visually, then in the image this process will look like this:


    Without the XMLHttpReques object, information cannot be exchanged, so it is pre-placed on the page itself. The object acts as a link between the server and the web browser. The requests themselves pass from the system to the server in POST format or GET. The GET type inherently refers to a document located on the server, and receives the site address as an argument. To prevent the request from being aborted, a robust JavaScript Escape function has been created to prevent such cases.

    If data is sent to large volumes, you can't do without the POST function. The server processes the information that it receives and then, based on it, generates updated data that is sent to the user.

    The AJAX approach involves transferring information at different times. Thanks to this client, the most different functions during “background” data transfer. The user receives a message about the process of transferring information so that he does not consider him stuck - this allows him to be kept on the site.

    To send the response, the server uses standard JSON or XML text. When receiving a JSON document, it is immediately displayed on the screen. But the user is also required to execute the code that he receives, after which a JavaScript object will be generated. And if the text is sent to XML format, it must first be replaced with HTML and then displayed on the page.

    What are the advantages of AJAX?
      • Reduces the load on the server. But this is only possible if the technology is used correctly. You can use a template that will help you create permanent elements of a web resource: menu, logo, header, etc. And to satisfy visitor requests, there is no need to reload the entire page. For example, you created a block with voting, and the visitor is asked to select the option that is optimal for him to vote. As soon as he presses the button, the information will immediately go to the server, and then the person will receive a response. And all this happens without refreshing the page.
      • Improves server performance. Because only the content of the page is loaded, and users receive the results of their actions much faster.
      • Reduces traffic. The amount of data when working with applications is significantly reduced. This is ensured by the fact that not the entire page is reloaded, but only its changed elements or data. The script then changes the information on the page in the browser.
      • Opens up a wide variety of possibilities. Once you choose AJAX, you'll have a plethora of actions available to you. Thus, when registering on sites, a visitor, indicating a login, immediately finds out whether he is busy or not. And by entering a request in search bar Google or Yandex, after any subsequent word or letter, are displayed below ready-made options requests. Of course, this makes the task much easier for Internet users.

    What are the disadvantages of the technology?
    • JavaScript must be enabled at all times. Without this support, AJAX technology on relevant pages is practically useless.
    • Problems with . Often, content placed dynamically on pages goes unnoticed by search bots. Because of this, it is recommended that dynamic loading be applied only to certain pieces of content. This is the only way to minimize Negative influence technologies for SEO promotion.
    • Cannot combine with browser tools. If you create pages dynamically, the browser will not remember them and show them in the history, and therefore, when you click the “Back” button, you will not return to the previously visited page. But the problem is being solved special scripts. You will also not have the opportunity to bookmark any content.
    • Lack of number of requests. Due to the dynamic loading of materials, the system cannot accurately display statistics because when the user navigates through different pages, they do not reload, and the counter does not count these transitions. Because of this, problems may arise when evaluating analytics on the site.
    • The level of security is reduced. By installing AJAX, any user can view the source code of the page, and this is not secure.
    How is AJAX indexed by search engines?

    It was already said above that pages based on this technology are very poorly indexed. To avoid this, it is better to make sure in advance that dynamically loaded data is available via links too. Having provided this possibility, the pages of the web resource will be displayed normally even for those users who are using a browser without JavaScript.

    Owners of sites where content is loaded dynamically need to make sure that search engine robots, in addition to understanding the content of the pages, also correctly determine the rules for navigating the site.

    To minimize the negative impact of AJAX on website promotion, it needs to be optimized:

  • Change the links in the URL. After all # symbols, write down the signs ! . For example, link http://mysite.com/#catalog change to http://www.mysite.com/#!catalog
  • Open access to HTML versions each AJAX page at specific addresses. To do this, change the value we set in them “#! " to "?_escaped_fragment_= ". The result will be http://www.mysite.com/?_escaped_fragment_=catalog
  • For AJAX pages enter the tag:
  • Create an xml map. This will speed up the indexing of site pages.
  • After the site is included in the index, look at the difference between the AJAX version and the copy. This way you can control which pages robots did not add to the search engine database. How to check site indexing, read.
  • How does technology affect rankings and is it worth using it on a website?

    Often, search engines treat AJAX resources worse than sites that do not use this technology. There are several reasons for this:

    • some content may not be indexed by robots;
    • all pages have the same url;
    • Certain pages may appear differently to search bots than to users.

    But if you use AJAX technology wisely, that is, use it only for certain fragments on the site, then you will not have problems with indexing.

    I would not recommend using AJAX technology for the entire site; such sites are poorly indexed by search engines. But for some user elements (for example, polls, adding comments), this technology is useful and, on the contrary, can increase the usability of your project.

    Conclusion

    AJAX technology opens huge opportunities for users, makes communication with websites much faster and more comfortable, increases the speed of their work. But she also has significant shortcomings, which can be avoided if used correctly. Only with a competent approach will your website rise to high positions in search results and be in good standing with search engines.

    AJAX stands for Asynchronous Javascript And XML, which means Asynchronous JavaScript and XML. AJAX allows you to update HTML page data without completely reloading it. In addition, the technology allows you to work with Internet pages asynchronously. That is, while JavaScript interacts with the Web server, the user can continue to work with the web page.

    An example of using AJAX technology is Google Suggest. Google work The Suggest thing is that while you are typing a word or phrase to search, JavaScript accesses the database Google data and asks her for the 10 most popular queries, starting with the same letters. And then displays this list without reloading the page.

    To consider the principles of operation of AJAX technology, we will implement a mechanism similar to Google Suggest on our website. Let's say we have a tour operator website. The site has a search field for suggestions by country name. Let's add a drop-down list to this field with auto-completion based on the entered letters. Let's start solving this problem. I’ll say right away that to implement this task you need knowledge of HTML and a little JavaScript (you don’t have to be an expert). As server language php will be used.

    First, let's create a search form. To do this, create a file index.html on your web server, open it using any text editor and enter the following html code.




    Search for offers.





    Holidays at sea

    Search for offers:








    In this listing, we created a search form with a text input field and a submit button, and created a div layer to display the results. An ajax.js file is also attached to this page, which will contain JavaScript functions.

    Next, we will write JavaScript functions that will send requests to the server and update the page. In order not to have to completely overload the HTML document, we need Ajax technology. So let's get started. Create an ajax.js file, place it in the same folder as index.html, and open it in a text editor.

    First, you need to create an object that will send requests to the server and receive responses. This object is created differently in different browsers. We will write a universal function that should work in different browsers. Add the following JavaScript code to your ajax.js file.

    /*variable for storing the request object*/
    var request;
    /*function for creating a request object*/
    function CreateRequest()
    {
    var request=null;
    try
    {
    //create a request object for Firefox, Opera, Safari
    request = new XMLHttpRequest();
    }
    catch(e)
    {
    //create a request object for Internet Explorer
    try
    ( request=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
    request=new ActiveXObject("Microsoft.XMLHTTP");
    }
    }
    return request;
    }

    You must display a list of results every time you change the search field. To do this, we will use the handler JavaScript events. We will detect changes at each keyboard event keyup . To do this, in our HTML code of the index.html file, in the line where a search field with the name country is created, add the onkeyup="KeyPress(this.value)" attribute:

    That is, when any key is pressed, the JavaScript KeyPress() function will be called, to which the characters entered in the search string are passed as a parameter. The KeyPress() function must perform the following tasks:

    • Create a new request object by calling the CreateRequest() function;
    • Generate the URL you need to connect to to get results;
    • Configure a request object to establish a connection with the server;
    • Send a request to the server.

    Let's start creating the KeyPress() function. To create a new request object, we simply need to assign the request variable the value returned by the previously created CreateRequest() function. And to be on the safe side, let’s check the request variable. If it is NULL, then the request object could not be created. This is what the JavaScript code to solve this problem will look like:

    Function KeyPress(term) (
    request=CreateRequest();

    if(request==null)
    {
    return;
    }
    }

    Next, you need to tell the request object which JavaScript function will process the server response. To do this, you need to assign the onreadystatechange property the name of the corresponding function. This property tells the browser which function to run whenever the request's ready state changes. Our LoadResults() function will process the response. Add the following line to the function: request.onreadystatechange = LoadResults; . Note that there are no parentheses after the function name.

    Then let's set up the connection. To do this, you first need to tell the object where to send this request. Let's create the URL of the script that will calculate the results and assign it to the url variable. Let's say that the php script country.php will be responsible for calculating the results on the server side. Then our URL will look like this: var url = "country.php" + "?s=" + encodeURIComponent(term) + "&sid=" + Math.random(); , where the variable s contains the characters entered in the search field, and sid is assigned a random number so that the browser does not cache the page. Add this line to the body of the KeyPress() function.

    Next, you need to initialize the connection using the open("GET", url, true) method of the request object. This method has three parameters. The "GET" parameter specifies how to send data to the server. We use the GET method because the characters entered into the search string are passed to the server script via the URL. The second parameter specifies the URL of the server script. We store the url address in the url variable, so we specify this variable in the second parameter. The third parameter can have two values: true - asynchronous mode and false - synchronous mode. Our application will work in asynchronous mode, so we specify true . After initializing the connection, you need to create the connection and query the results. To do this, you simply need to call the send(null) function on the request object. The null parameter indicates that the request contains no data.

    After making all the changes, the KeyPress(this.value) function will look like this:

    Function KeyPress(term)
    {
    /*create a new request object*/
    request=CreateRequest();
    /*if it was not possible to create a request object, then we finish executing the function*/
    if(request==null)
    {
    return;
    }
    /*form the URL*/
    var url = "country.php" + "?s=" + encodeURIComponent(term) + "&sid=" + Math.random();
    /*set up a request object to establish a connection*/
    request.onreadystatechange = LoadResults;
    request.open("GET", url, true);
    /*send a request to the server*/
    request.send(null);
    }

    So, the connection is established, the request is sent, the server processes the data and returns the result. Next, you need to receive a response, process and display the results on a web page. All this will be done by the LoadResults() function, which will be called whenever the request readiness status changes. Let's look at how this function should work.

    First, you need to check the current state of readiness. The ready status is stored by the request object's readyState property. When the request is processed, the ready status is 4. That is, if request.readyState == 4 , then you can process the response:

    Function LoadResults()
    {


    /*process the response*/
    }
    }

    Function LoadResults()
    {
    /*Checking the readiness status*/
    if (request.readyState == 4)(
    /*Checking the status of the request*/
    if (request.status == 200)(
    /*everything is fine, processing the response*/
    }
    }
    }

    If checking the status and status of the request is completed successfully, then you can begin processing the data received from the server. You can receive data in two ways: request.responseText - receiving data in the form of text, or request.responseXML - receiving data in the form of an XMLDocument object. Let's say our server sends a response in the form of a text list of countries separated by commas. Then we get the data: var answer = request.responseText . Next, we process the data and display it in a layer with id="searchresults" .

    I will not go into details of data processing, but will simply provide the function code with comments:

    Function LoadResults()
    {
    /*Checking the readiness status*/
    if (request.readyState == 4)(
    /*Checking the status of the request*/
    if (request.status == 200)(
    //make the searchresults layer visible
    ShowDiv("searchresults");
    //clear the results
    ClearResults();
    //get data
    var answer = request.responseText;
    //convert a string of text into an array
    var array = answer.split(",");
    //determine the size of the array
    var count = array.length;
    //find the searchresults layer

    //create a table in the document object model
    var tbl = document.createElement("table");
    var tblbody = document.createElement("tbody");
    var tblRow, tblCell, tblNode;
    // iterate through all elements of the array array
    for(var i = 0; i (
    var text = array[i];
    //create table rows and add them to its body
    tblRow = document.createElement("tr");
    tblCell = document.createElement("td");
    //set the attributes and functions of cells
    tblCell.onmouseover = function())(this.className="mouseOver";);
    tblCell.onmouseout = function())(this.className="mouseOut";);
    tblCell.setAttribute("border", "0");
    tblCell.onclick = function())(Replace(this););
    tblNode = document.createTextNode(text);
    tblCell.appendChild(tblNode);
    tblRow.appendChild(tblCell);
    tblbody.appendChild(tblRow);
    }
    //add her body to the table
    tbl.appendChild(tblbody);
    //place the table in the layer
    div.appendChild(tbl);
    }
    }
    }

    And a couple more auxiliary JavaScript functions to display the results on the screen:

    /*make the results layer visible*/
    function ShowDiv(id)
    {
    if (document.layers) document.layers.visibility="show";
    else document.getElementById(id).style.visibility="visible";
    }

    /*make the layer with the results invisible*/
    function HideDiv(id)
    {
    if (document.layers) document.layers.visibility="hide";
    else document.getElementById(id).style.visibility="hidden";
    }

    /*clear results*/
    function ClearResults()
    {
    /* Delete existing rows from the results table
    var div = document.getElementById("searchresults");
    var counter = div.childNodes.length;
    for(var i = counter-1; i >= 0; i--)
    {
    div.removeChild(div.childNodes[i]);
    }
    }

    /*Replace the value in the input field with the value selected by mouse click*/
    function Replace(tblCell)
    {
    var inputbox = document.getElementById("country");
    inputbox.value = tblCell.firstChild.nodeValue;
    ClearResults();
    HideDiv("searchresults");
    }

    Also in our html file index.html between the tags and add the following CSS rules:


    .mouseOut( background: #ffffff; color: #0000000; )
    .mouseOver( background: #ccccff; color: #0000000; )
    table (width:250px )

    That's all. In this article, we looked at the basics of Ajax technology using an example.





    

    2024 gtavrl.ru.