Crmgo Blog

AJAX. Basics.

AJAX. Basics.

AJAX (Ajax) is a web technology that allows interaction with the server without reloading the page. Examples of its use include checking username availability during registration, adding items to the shopping cart without page reload, Google Suggest, and so on. AJAX is based on the XMLHttpRequest object. As you can see...

AJAX. Basics.

AJAX is a web technology that allows interaction with the server without reloading the page. Examples of its use include checking username availability during registration, adding items to the shopping cart without reloading the page, Google Suggest, and so on. AJAX is based on the XMLHttpRequest object. As the name suggests, it was designed for working with XML, although this does not prevent its use for other purposes.

The principle of operation is as follows:
The script consists of two parts:

  1. client-side part: executed on the client side, written in JavaScript
  2. server-side part: executed on the server, can be written in any programming language that understands GET/POST requests

Steps for writing the client-side part:

  1. collect and prepare the information to send the request to the server;
  2. create an instance of the XMLHttpRequest object;
  3. assign an onreadystatechange event handler function to it. This event occurs every time the state of the XMLHttpRequest object changes (see the table below). This function is essentially the main part of the script, as it is where the server response is processed;
  4. open the connection by specifying the request type (GET or POST), the URL of the server-side part, the asynchronous mode flag, and the username and password (if required);
  5. send the request;
  6. process the server-side response.

Creating the XMLHttpRequest object differs between Internet Explorer and other browsers, so for compatibility, this operation must be duplicated in different ways:

01var req;
02
03if (window.XMLHttpRequest)  // normal browser
04req = new XMLHttpRequest();  
05else if (window.ActiveXObject) {    //IE
06try {
07req = new ActiveXObject('Msxml2.XMLHTTP');  // IE разных версий
08} catch (e){}                                   // может создавать
09try {                                           // объект по разному
10req = new ActiveXObject('Microsoft.XMLHTTP');
11} catch (e){}
12}

Using the GET method, setting the onreadystatechange event handler, and sending the request:

1req.open("GET", url, true);
2req.onreadystatechange = function() {
3if (req.readyState == 4)  { обработка результатов }       
4}; 
5req.send(null); //отправка запроса без параметров, т.к. они установлены в url     

In the onreadystatechange event handler, it is necessary to check the condition req.readyState == 4, which indicates that the data has been loaded. Additionally, you can also check req.status == 200. See the tables below.

When using the XMLHttpRequest object with the POST method, it is additionally required to send a header:

1req.open("POST", url, true);
2req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
3req.onreadystatechange = function() {
4if (req.readyState == 4)  { обработка результатов }       
5};     
6req.send('param1=1¶m2=0'); //теперь параметры передаются здесь

Several parameters are separated by ampersands.

Full example:

01var req;
02
03if (window.XMLHttpRequest) req = new XMLHttpRequest();
04else if (window.ActiveXObject) {
05try {
06req = new ActiveXObject('Msxml2.XMLHTTP');
07} catch (e){}
08try {
09req = new ActiveXObject('Microsoft.XMLHTTP');
10} catch (e){}
11}
12
13if (req) {
14req.onreadystatechange = function() {
15if (req.readyState == 4 && req.status == 200)  { alert(req.responseText); }       
16}; 
17req.open("POST", 'xmlhttp.php', true);
18req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
19req.send('param=1&ajax=1');
20}
21else alert("Браузер не поддерживает AJAX");

The server-side part (the URL in req.open) can be written in any language, as long as it understands GET/POST requests. The returned value (req.responseText) is formed by standard output. Here is an example of a server-side script in PHP:

1if(isset($_POST['param']))
2echo ($_SERVER['REMOTE_ADDR'])?"Your IP ".$_SERVER['REMOTE_ADDR']:"IP неизвестен";

article here

A few reference materials:

XMLHttpRequest class methods

Method Description
abort() cancels the current request
getAllResponseHeaders() returns the full list of HTTP headers as a string
getResponseHeader(headerName) returns the value of the specified header
open(method, URL, async, userName, password) specifies the method, URL, and other optional request parameters; the async parameter determines whether the operation is performed asynchronously
send(content) sends the request to the server
setRequestHeader(label, value) adds an HTTP header to the request
overrideMimeType(mimeType) allows you to specify the document's MIME type if the server did not send it or sent it incorrectly. Note: this method is not available in Internet Explorer!

XMLHttpRequest Class Properties

Property Description
onreadystatechange event handler that is triggered each time the object's state changes
readyState returns the current state of the object (0 — uninitialized, 1 — open, 2 — sending data, 3 — receiving data, and 4 — data loaded)
responseText the text of the response to the request
responseXML the response to the request in XML format, which can then be parsed using the DOM
status returns the HTTP status as a number (404 — "Not Found", 200 — "OK", etc.)
statusText returns the status as a string ("Not Found", "OK", etc.)

Note: This post may be AI-assisted and then human-edited. Editorial responsibility: Dmytro Lomaka, Kaltenkirchen.