ComputersProgramming

Ajax are examples. Ajax scripts

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

It does not matter if the resource reacts to a visit static or creates a response dynamically. Even if the type and content of the page depends 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 "managed" to receive, parse and execute.

Many promising technologies have appeared for a long time, but have been 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 classical version of the site - the name, IP-address and link (all these are synonyms, denoting the same point in the Internet space). The fact that this is the main page of the site - thought up on its own initiative a modern "developer" who did not even ask himself the question: why exactly? Why is the site the main page from which you can get to any other? Such an option is clearly not an ideal, it is a concrete content and an actual functional.

Simply put, if a person needs a dentist, he goes to the right address for a specific purpose, and not to the kitchen for surgical intervention and not to the library for the advice of the therapist. In the place where this someone happened to be, he will see, but he will not get a dental polyclinic in full. The maximum that a visitor can count on is the registry and the direction (the exact path) to the doctor. And on the spot (on arrival) can change both the doctor and the destination.

But here the site is usually always loaded in a full ammunition, nothing changes with the fact of loading, taking into account the time of the one who came ... And even if it is a resource of a real clinic, when you first visit a new client it is enough to give an information page , Contacts and the registry window ... You can foresee that the visit to the site was done outside of working hours, and the appointed doctor is absent, the reception is temporarily made in a different room ...

Point in the Internet space

The classical reaction of the resource of the Internet space - in response to a request to issue a page of the site (usually the main page), and then others, at the request of the visitor. The site server also contains images, styles, JavaScript code scripts, PHP, etc. Not all PHP files make pages, some of them can respond to AJAX requests: receive, process and send information.

It is not difficult to write a script. But, getting control on a point in the Internet space, it is impossible to determine who and for what matter addressed, 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 different origins and destinations, through the actions of other sites.

The script that received the control can know for sure only: the time of the visit, through which browser the visitor came, from which link, from which IP address and the presence of cookies. Only the latter can give 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 the general response of the server. AJAX-examples that are easy to find on the Internet should be used carefully. Errors in the operation (use) of the XMLHttpRequest object are difficult to track.

Common response and private dialogue

The general response of the server is a normal page, called the main page of what is called index and the site begins with it, that is, links to other accessible pages differ from it. However, if the visitor knows the names of these other pages, they in his understanding will be no less important than the one designated by the developer. So it looks like a classic model, everything at once: a common design and functionality, aimed at all visitors.

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

There are two basic requests to the server for downloading the site and working with it: POST and GET. The result of the query is the entire page. On the received page, the visitor can activate certain events configured for actions on certain elements of the page.

Page Element Events

A page element can be a button for finding information, meaning - take the contents of the text field and find what the visitor wrote in it. An event can occur on a menu item, a drawing, or a 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 (variable var scXHR should 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 a URL and initiates a request for it. The asynchronous response will come as soon as the script specified in the URL executes (in this case - scSrvPhpWord.php located in the ../Mphp/ folder relative to the site root), and the WaitReplySC () function will start, the input of which will be the server's XML response, Including the title and content.

Server Response

Actually the server is a PHP script - a program that starts with the installation of essential conditions, downloading the necessary objects, preliminary preparation, which depends on the developer's goals:

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 start indicates the mark of all errors, prohibits stopping the script when the user is disconnected, and sets the run-time limit for the case of looping - 12 seconds. Next, the PhpOffice \ PhpWord library is connected to work with * .docx documents.

Because the above AJAX call ('... cTask = GoPage' + '& cOwnerCode =' + cOwnerCode + '& cSessionCode =' + cSessionCode + '& cActiveItem =' + cActiveItem) are four GET variables that may not exist, You should 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 performing the preparatory actions, the script makes a decision:

Switch ($ cTask) {

Case 'GoPage': // (this is a call when the page is initially loaded or refreshed)

$ 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 '';
$ CReply = iconv ('CP1251', 'UTF-8', $ cReply); // conversion from 'CP1251' to 'UTF-8'
Echo $ cReply;

Receiving a response from the client

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

Function WaitReplySC () {

Try {

If (scXHR.readyState == 4) {
If (scXHR.status == 200) {// handle the response

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]; // the server's HTML response
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 the submitted code, jQuery and WordPress

The page in the browser and the text of the script 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 particular purpose.

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

Presented AJAX-examples are focused on "manual" use of technology.

In the various site management system (SMS) 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 passed to url and settings (a set of key-value pairs). JQuery.ajax () returns an XMLHttpRequest object.

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

The jqXHR.done () method is an alternative to the handler for the successful completion of the AJAX request. Replaces the obsolete method jqXHR.success ().

Similarly, the use of AJAX technology on WordPress. Here everything is already implanted in the site management system itself, you only need to use the proposed designs. The documentation is offered a detailed description.

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

A classic example of application

A simple and demonstrative use of AJAX is a shopping cart in an online store. The pages of the store are always filled with goods, although in reality they may not be. Reboot normally takes a significant amount of time, but when a visitor selects a product, he can always refuse from it at once or change it to another, which is always desirable to display on the site quickly.

Usually this is realized in the form of a basket and marks near the selected goods. Without the use of AJAX, a dynamic change in these elements is problematic.

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

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


Name:
Password:




Login

Here is 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 to the server to verify the visitor's entered name and password. The script checks the presence of the information received in the user table and sends back the answer, on the basis of which the corresponding script on the page displays a message (performs an action) for the registered visitor or informs that there is no such user and it is necessary to complete the registration procedure.

Similar articles

 

 

 

 

Trending Now

 

 

 

 

Newest

Copyright © 2018 en.birmiss.com. Theme powered by WordPress.