Ajax - examples. Ajax scripts

The Internet provides the visitor with the visibility of each resource that is hosted on the network, and the browser with access through network protocols, mechanisms for invoking individual scripts, and transmitting / receiving information. The set of pages that make up the site has a common root - a unique link (domain name, unique node address).

It doesn't matter if the resource responds to the visit statically or dynamically creates a response. Even if the type and content of the page depend on any conditions, an indivisible unit of communication between the server and the client (browser) is a complete HTML document with code, pictures, style sheets, files and other necessary content and surroundings. If something is wrong here, the browser will display everything that it has “managed” to receive, disassemble and execute.

ajax examples

Many promising technologies appeared a long time ago, but were undeservedly forgotten or not used properly. The first AJAX (examples of using the XMLHttpRequest object) appeared many years ago, but success and fame came much later.

All at once or just what you need

In the classic version, the site is a name, IP address and link (all these are synonyms denoting the same point in the Internet space). That behind this lies the main page of the site - the modern "developer" thought up on his own initiative, who did not even ask himself: why is this so? Why is the site the main page from which you can get to any other? This option is clearly not ideal, it is a specific content and actual functionality.

jquery ajax

Simply put, if a person needs a dentist, he goes to the right address for a specific purpose, and not to the kitchen for surgery and not to the library for a consultation with a therapist. In the place where this someone was, he will see, but will not receive a dental clinic in full. The maximum that a visitor can count on is the registry and the direction (exact path) to the doctor. Moreover, both the doctor and the destination can change at the place (upon arrival).

But here the site is usually always loaded in full ammunition, nothing changes upon loading, taking into account the time of the one who arrived ... But even if it is a resource of a real clinic, it’s enough to give a page of information on the first visit to a new client , contacts and the registration window ... It can be envisaged that a visit to the site was made after hours, and there is no designated doctor, the appointment is temporarily made in another office ...

Point in the Internet

The classic reaction of an Internet space resource is to respond to a request with a page of the site (usually the main one), and then others, at the request of the visitor. The site server also contains pictures, styles, JavaScript, PHP, and other script codes. Not all PHP files make pages, some of them can respond to AJAX requests: receive, process and send information.

Writing a script is easy. But, getting control at a point in the Internet space, it is impossible to determine who contacted for what reason, that is, activated this name, IP address and link. Any movement on the network occurs programmatically, mainly through the browser, but also through robots of various origins and purposes, through the actions of other sites.

The script that got control can only know for sure: the time of the visit, through which browser the visitor came in, from which link, from which IP address and the presence of cookies. Only the latter can provide information on how to form the main page, but only if this visitor has already been here. In all other situations, it is possible to generate only a general server response. AJAX examples that are easy to find on the Internet should be used carefully. Errors in the operation (use) of the XMLHttpRequest object are not easy to track.

General answer and private dialogue

The general response of the server is a regular page, called the main page from what is called index and the site starts from it, that is, links to other available pages diverge from it. However, if the visitor knows the names of these other pages, in their understanding they will be no less important than the one designated by the developer. It looks like a classic model, everything at once: the overall design and functionality, focused on all visitors.

Private dialogue is a continuation of the previous visitor session. The site already knows what it was doing, what interests it, what pages were viewed and put it in its memory, wrote something in the browser cookies.

Two main requests to the server are used to load the site and work with it: POST and GET. The result of the query is the entire page. On the received page, the visitor can activate certain events that are configured to act on certain elements of the page.

wordpress ajax

Page Item Events

An element of a page can be a button for finding information, meaning - take the contents of a text field and find what the visitor wrote in it. An event can occur on a menu item, picture, text field. In any case, a JavaScript function will be launched that can execute the AJAX request as follows:

InitXML ('../ Mphp / scSrvPhpWord.php? CTask = GoPage' + '& cOwnerCode =' + cOwnerCode
+ '& cSessionCode =' + cSessionCode + '& cActiveItem =' + cActiveItem);

In this case, the InitXML () function is defined as follows (the var variable scXHR must be described outside the function):

function InitXML (scURL) {

scXHR = null;

if (window.XMLHttpRequest)
{try
{scXHR = new XMLHttpRequest ();
} catch (e) {}
} else
if (window.ActiveXObject)
{try
{scXHR = new ActiveXObject ('Msxml2.XMLHTTP');
} catch (e)
{try
{scXHR = new ActiveXObject ('Microsoft.XMLHTTP');
} catch (e) {}
}
}
if (scXHR)
{
scXHR.open ('GET', scURL);
scXHR.onreadystatechange = WaitReplySC;
scXHR.send (null);
};
}

This function receives the URL and initiates a request on it. An asynchronous response will come as soon as the script specified in the URL (in this case scSrvPhpWord.php located in the ../Mphp/ folder relative to the root site) is executed, and the WaitReplySC () function is launched, the input of which is the server’s XML response, including title and content.

ajax basket

Server response

The server itself is a PHP script - a program that starts with setting the essential conditions, loading the necessary objects, preliminary preparation, which depends on the goals of the developer:

namespace PhpOffice \ PhpWord;

ini_set ('display_errors', 1);
error_reporting (E_ALL ^ ​​E_NOTICE);

ignore_user_abort (true);
set_time_limit (12);

use PhpOffice \ PhpWord \ MphpObj \ scDocuments;

require_once 'PhpOffice / PhpWord / Autoloader.php';
\ PhpOffice \ PhpWord \ Autoloader :: register ();

The presented beginning indicates the mark of all errors, prohibits stopping the script when the user is disconnected, and sets a run time limit in case of a loop - 12 seconds. Next, the PhpOffice \ PhpWord library is connected to work with * .docx documents.

Since the AJAX call shown above ('... cTask = GoPage' + '& cOwnerCode =' + cOwnerCode + '& cSessionCode =' + cSessionCode + '& cActiveItem =' + cActiveItem) are four GET variables that may not exist, check their actual availability:

$ cTask = (isset ($ _ GET ['cTask']))? $ _GET ['cTask']: '';
$ cOwnerCode = (isset ($ _ GET ['cOwnerCode']))? $ _GET ['cOwnerCode']: '';
$ cSessionCode = (isset ($ _ GET ['cSessionCode']))? $ _GET ['cSessionCode']: '';
$ cActiveItem = (isset ($ _ GET ['cActiveItem']))? $ _GET ['cActiveItem']: '';

After completing the preparatory steps, the script decides:

switch ($ cTask) {

case 'GoPage': // (this is a call on the initial page load or refresh)

$ cOwnerCode = 'cOwner';
$ cSessionCode = 'cSession';
$ cContents = 'cContents';
$ cStatus = 'cStatus';
$ cHtml = iconv ('UTF-8', 'CP1251', 'element encoding');
$ cActiveItem = iconv ('UTF-8', 'CP1251', 'variable values');

$ cReply = "scSrvRM | GoPage | set | {$ cOwnerCode}` {$ cSessionCode} | {$ cContents} `{$ cStatus} | {$ cHtml} | {$ cActiveItem}";

break;

}

and the final part of the script:

header ("Content-Type: text / xml; accept-charset = utf-8");
header ("Cache-Control: no-cache");
echo '<? xml version = "1.0" encoding = "UTF-8"?>';
$ cReply = iconv ('CP1251', 'UTF-8', $ cReply); // convert from 'CP1251' to 'UTF-8'
echo $ cReply;

Client response

On the page loaded into the browser, it was found that as soon as the server prepares the response, it will be processed by the WaitReplySC function:

function WaitReplySC () {

try {

if (scXHR.readyState == 4) {
if (scXHR.status == 200) {// response processing

var TestReply = scXHR.responseText;

if ((TestReply.indexOf ('Parse error')> 0) ||
(TestReply.indexOf ('Notice')> 0)) alert (scXHR.responseText);

var cData = scXHR.responseText;
var aData = cData.split ('|');

var cCmd = aData [1];
var cPos = aData [2];
var aOwnerSession = aData [3] .split ('' ');
cOwnerCode = aOwnerSession [0];
var cSessionCode = aOwnerSession [1];
var aContentStatus = aData [4] .split ('' ');
var cContent = aContentStatus [0];
var cStatus = aContentStatus [1];
var cHTML = aData [5]; // HTML response of the server
var cVarValues ​​= aData [6]; // values ​​of variables for forms

switch (cCmd) {

case 'GoPage':

var dTestLine = document.getElementById ('scTestLine');
dTestLine.innerHTML = 'Reply = [' + cOwnerCode + ','
+ cSessionCode + ','
+ cContent + ','
+ cStatus + ','
+ cHTML + ','
+ cVarValues ​​+ ']';

break;
}

} else {
document.getElementById ('scAreaStatus'). innerHTML = "Error !!!";
}
}
} catch (e) {}

}

Thus, using these AJAX examples, when loading the page in the browser, we get (in the scTestLine element):

Reply = [cOwner, cSession, cContents, cStatus, element encoding, variable values]

About submitted code, jQuery and WordPress

The page in the browser and the script text are written in UTF-8 encoding, therefore the iconv () function is used to convert Russian letters. Otherwise, the skeleton of the presented code is very simple and can easily be repeated for any specific purpose.

Only the server response processing in the WaitReplySC () function and the actual script code that generates this response are subject to change. InitXML function calls (for a particular scURL and its corresponding data) are placed in event handlers on page elements and determine the semantic load of these elements.

The presented AJAX examples are focused on the “manual” use of technology.

In various site management systems (SMS), the described features are presented in different ways, usually in the style of one or another specificity. For example, jQuery AJAX features are implemented by calling jQuery.ajax () functions or a higher level: jQuery.get () and jQuery.post (). The parameter is url and settings (a set of key + value pairs). jQuery.ajax () returns an XMLHttpRequest object.

ajax scripts

To track the result, jQuery offers a function function: XHR.done () - successful completion of the request. XHR.fail () - error handling.

The jqXHR.done () method is an alternative to the AJAX request success handler. Replaces the deprecated jqXHR.success () method.

write a script

The use of AJAX technology on Wordpress is similar. Here, everything has already been implanted into the content management system itself, you only need to use the proposed designs. The documentation offers a detailed description.

The use of AJAX significantly depends on the chosen toolkit, although the manual version can be applied in parallel or in addition to the selected site management system, one or another version of jQuery. The latter is useful to work on their own, since almost all modern SMS use it, but each in its own way.

Classic application example

A simple and illustrative application of AJAX - basket in the online store. The store’s pages are always full of goods, although in reality they may not be. Rebooting usually takes a considerable amount of time, but when a visitor selects a product, he can always immediately refuse it or change the one chosen by another, which is always desirable to display quickly on the site.

ajax form

Usually this is implemented in the form of a basket and marks next to the selected goods. Without using AJAX, dynamically changing these elements is problematic.

AJAX scripts that implement mechanisms for adding / removing goods to the basket have become de facto in many SMS.

For regular data transfer via AJAX, the form can be executed in the usual way (for entering a name and password):

<form name = 'fWelcome' action = 'index.php' method = 'post'>
<div id = 'scWelcomeLabel' style = 'left: 0px; top: 12px; '> Name: </div>
<div id = 'scWelcomeLabel' style = 'left: 0px; top: 35px; '> Password: </div>
<input type = 'text' name = 'cName' value = '' id = 'scWelcomeField' title = 'Name' style = 'left: 56px; top: 8px; '>
<input type = 'text' name = 'cPass' value =' 'id =' scWelcomeField 'title =' Password 'style =' left: 56px; top: 31px; '>
</form>
<div id = 'scWinClose' onclick = 'JavaScript: scfWelcomeCancel ();' title = 'Close window'> </div>
<div id = 'scWelcomeGo' onclick = 'JavaScript: scfWelcomeGo ();'> Login </div>

Here's the handler:

function scfWelcomeGo () {

var cName = document.fWelcome.cName.value;
var cPass = document.fWelcome.cPass.value;

InitXML ('../ Mphp / scSrvPhpWord.php? CTask = CheckWelcome'
+ '& cName =' + cName
+ '& cPass =' ​​+ cPass);

}

sends the username and password entered by the visitor to the server for verification. The script checks the availability of the information received in the user table and sends back a response based on which the corresponding script on the page displays a message (performs an action) for the registered visitor or reports that there is no such user, and you need to go through the registration procedure.

Source: https://habr.com/ru/post/K10357/


All Articles