Ajax inserting html code. Using Ajax. Controlling data transformation

From this article you will learn how you can display any html code through the special AJAX technology. This is not very easy and requires some knowledge, but do not worry that you will not succeed. Below will be given detailed instructions, according to which even a beginner can figure it out. Before proceeding directly to the instructions, I will answer the question, why is this needed in general and what options are there.

In general, there are two ways to display content: either through JavaScript or through AJAX. My opinion is that it's better to use AJAX than JS, but why is it better, you ask? After all, both technologies hide the text in separate files. And the answer is that search engines have come to a very high level and is already able to determine the links that are contained in the javascript. For example, Google has already announced this, apparently soon Yandex will also announce this achievement.

Instructions for displaying content via AJAX

1. Add to header directory the following script:

... ...

Это нужно, чтобы подключить необходимые библиотеки для работы AJAX прямо с официального сайта.

2. Создайте html или php документ с кодом, который нужно выводить через AJAX . Например, создадим файл text-dlya-ajax.html и пропишем в нем:

Этот <b >текст будет выведен через AJAX

3. Создайте отдельный файл JavaScript (.js). Обычно я его называю ajax.js , чтобы сразу понять его содержимое. Добавьте в него следующий код:

(function($) { $(function() { $("#blockajax").load("СЮДА_ПРОПИСЫВАЕМ_ПУТЬ_К_ФАЙЛУ_html/text-dlya-ajax.html"); }) })(jQuery)

Теперь blockajax будет характеризоваться файлом text-dlya-ajax.html .

Примечание

Если нужно вывести много таких привязок "блок" = "html-код", то можно прописать сколь угодно много различных соответствий:

(function($) { $(function() { $("#block1").load("block1.html"); $("#block2").load("block2.php"); ................................. $("#blockN").load("blockN.html"); }) })(jQuery)

4. Подключите файл ajax.js к документу через заголовочный тег :

... ...

Важно, чтобы сначала подключалась библиотека jquery.min.js, а уже потом файл ajax.js. Иначе работать не будет. Должно быть так:

... ...

5. В месте где нужно вывести html-текст файла text-dlya-ajax.html напишите:

Вместо

подгрузиться наш html-код из файла text-dlya-ajax.html . Главная идея: скрывать ненужный код. В итоге кода на странице нету, а вывод нужного нам контента есть.

Больше делать ничего не требуется. Теперь Вы можете легко выводить контент через AJAX .

Вы можете скачать выше описанный пример по следующей ссылке: ajax.rar

Примечание

Кстати, через AJAX также можно выводить и интерпретировать PHP-код. А это открывает огромные возможности перед Вами.

Зачем нужно выводить html с помощью AJAX (3 причины)
1. Если быть очень кратким, то это нужно для продвижения сайта в поисковых системах. Дело в том, что ссылки внутри сайта как бы передают вес между собой. Те страницы на кого ссылаются чаще, имеют больший вес. Поэтому чтобы более равномерно распределить вес сайта между страницами (а не сливать его весь по сквозным ссылкам) нужно как-то сделать так, чтобы эти сквозные ссылки не учитывались поисковыми машинами.

Например, на многих сайтах можно встретить ссылки на метки, которые стоят на каждой странице сайта в сайдбаре. Получается, что страницы с метками имеют наибольшие веса, хотя не содержат важной информации. Также сюда можно отнести другие лишние ссылки на страницах, которые в принципе не нужны.

Конечно, можно закрыть все ссылки в метках в , однако исследования показали, что таким способом теряется вес на сайте, т.е. этот вес никому не передается, он как бы просто испаряется (звучит странно, но это так).

2. Второй причиной использования выводить html через AJAX является уменьшение кода на странице сайта. Опять таки это нужно для поисковых систем. Например, футер сайта постоянно дублирует один и тот же код, который только отнимает лишний вес со страницы, поэтому было бы хорошо этот код убрать, но футер оставить. Аякс идеально подходит для решения этой проблемы.

3. Страница с использованием AJAX грузится поблочно, то есть каждый элемент как бы грузиться синхронно и не зависит от других. Таким образом "тяжелые" элементы на сайте не будут тормозить загрузку других частей сайта. Это более удобно для пользователя, поскольку он видит, что сайт грузится и чувствует себя более спокойно, нежели когда загрузка сайта на чем-то застопорилась.

В этой статье примеры кода, которые я использую, для отправки ajax-запросов к серверу через jQuery. Их задачи могут быть разными, поэтому под них можно использовать разные функции, которые упрощают написание кода.

Запрос html-данных с помощью функции Load

Это самый простой ajax-запрос через jQuery с получением html-данных и их вставкой в dom-элемент с id="result" (содержимое элемента заменяется):

$("#result").load("");

Более продвинутый вариант использования load:

$("#result").load("", {par1:val1, par2:val2, ...}, function(response, status, xhr) { if (status == "success") { alert("Готово"); } else { alert("Ошибка: " + xhr.status + " " + xhr.statusText); } });

В этом примере серверу так же передаются параметры, а после получения ответа проверяется не было ли ошибки (например, ответ от сервера не был получен) и выполнение различных действий.

Ajax-запросы функциями GET и POST

Эти функции осуществляют отправку ajax запроса http-методами get и post. Приведу пару примеров их использования.

$.get("", // адрес отправки запроса {par1:val1, par2:val2, ...}, // передача с запросом каких-нибудь данных function(data) { // какие-то действия с полученными от сервера данными data });

Передача данных не обязательна, как и выполнение каких-либо действий после получения ответа от сервера, т.е. в этом случае, строчки 3 и 4-6 можно удалить при необходимости и таким образом еще сократить код.

Тип получаемых от сервера данных можно указать, добавив dataType (см.ниже) - по-умолчанию определяется автоматически.

Использование post аналогично, но в следующем примере использую вызов функции после получения ответа от сервера.

$.post("", {par1:val1, par2:val2, ...}, onSuccess); function onSuccess(data) { // какие-то действия с полученными от сервера данными data }

На самом деле, функции get и post являются сокращенными вариантами функции ajax, которую рассмотрю ниже.

Получение json-данных с помощью getJSON

getJSON - укороченный вариант ajax-запроса методом GET и получением данных в виде json. Способ удобен, например, для получения какого-то массива с данными и последующей работы с ним.

$.getJSON("", {par1:val1, par2:val2, ...}).success(function(data) { // что-то делаем с данными, например, обходим их в цикле и выводим: for (var i=0; i

На стороне сервера программа формирует массив и преобразовывает его в json-строку, например, так:

$arr = array(); $arr = array("id" => 10, "text" => "тестовая строка 1"); $arr = array("id" => 20, "text" => "тестовая строка 2"); $arr = array("id" => 30, "text" => "тестовая строка 3"); echo json_encode($arr);

Точно так же можно передать с сервера и объекты stdClass, преобразовав их в json-строку.

Простой ajax-запрос через jQuery с помощью функции AJAX

Теперь приведу пример простого get запроса функцией ajax и получением html-данных.

$.ajax({ url: "", dataType: "html", success: function(data) { // какие-то действия с полученными данными data } });

Запрос к серверу происходит get-методом, т.к. параметр, отвечающий за тип запроса, type по-умолчанию равен GET.

Более сложный пример ajax-запроса через jQuery

Пример выполнения запроса функцией ajax с передачей данных post методом и обработкой событий. Ниже опишу дополнительные параметры, которые чаще всего применяются.

$.ajax({ url: "", type: "post", data: "<отправляемые_данные>", // можно строкой, а можно, например, так: $("input, input:checked, input:checked, select, textarea") dataType: "json", beforeSend: function() { $("#sendajax").button("loading"); }, complete: function() { $("#sendajax").button("reset"); }, success: function(json) { // какие-то действия с полученными данными }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } });

Кнопка отправки данных:

В приведенном примере при нажатии на кнопку button, сначала меняется состояние кнопки (текст на ней меняется на "Отправка..." и она становится не активной), что делается при помощи параметра beforeSend. Затем происходит отправка запроса с передачей нужных данных. После того, как получен ответ от сервера состояние кнопки возвращается в прежнее (текст меняется на "Отправить", становится активной). Ответ получается в виде json-данных.

Коротко опишу параметры отправки ajax-запроса, которые чаще всего могут пригодиться:

url Адрес отправки ajax-запроса
type Способ отправки запроса GET или POST
data Отправляемые серверу данные. Может быть строка с параметрами и их значениями в формате par1=val1&par2=val2&..., объект jQuery, например, $("input") или другие данные.
dataType Тип получаемых от сервера данных. Может быть html, json, text, script и xml.
cache Кэширование браузером запроса (false - не кэшировать).
async Асинхронное выполнение запроса, т.е. программа продолжает выполняться не дожидаясь ответа сервера. Если указать false, то запрос будет выполнен синхронно, при этом страница не будет ни на что реагировать, пока не будет получен ответ от сервера.
processData Преобразование отправляемых данных в url-формат. Если нужно чтобы данные не преобразовывались, установить в false. Например, при отправке изображения на сервер или xml-данных.
contentType Тип передаваемых данных, по умолчанию "application/x-www-form-urlencoded; charset=UTF-8". Если указать false, то в заголовке не будет передаваться тип, что может быть необходимо, например, при отправке изображения на сервер.
beforeSend Функция, выполняемая перед отправкой ajax-запроса.
complete Функция, выполняемая после получения ответа от сервера (любого, успешного или нет).
success Функция, выполняемая при удачном выполнении запроса.
error Функция, выполняемая в случае ошибки.

Ниже приведу еще несколько примеров использования ajax-запросов.

Отправка формы со всеми данными ajax-запросом через jQuery

Примерный код html-формы:

JavaScript код:

$("#myform").submit(function(e) { e.preventDefault(); $.ajax({ type: $(this).attr("method"), url: "", data: $(this).serialize(), async: false, dataType: "html", success: function(result){ alert("Форма отправлена"); } }); });

Для того чтобы страница не перезагружалась при нажатии на кнопку "submit", сначала отменяем стандартые действия браузера использовав e.preventDefaults() .

В параметре data мы передаем все поля формы использовав $(this).serialize() - эта функция преобразует все input-ы и select-ы в строку, пригодную для отправки на сервер.

Так же, здесь использован параметр async: false , чтобы пока форма не отправится на сервер больше ничего нельзя было нажать или сделать.

Отправка изображения или файла ajax-запросом через jQuery

Задача отправки файла или изображения на сервер без перезагрузки страницы довольно часто возникает. В этом примере разберу сразу 2 фишки: выбор файла по нажатию на кнопку , которая может быть оформлена как угодно, и отображение прогресса при передаче файла на сервер ajax-запросом.

html-код будет такой:

#addfile { position: relative; overflow: hidden; width: 180px; height: 34px; } #load_file { position: absolute; top: 0; left: 0; width: 180px; height: 34px; font-size: 0px; opacity: 0; filter: alpha(opacity:0); } #load_file:hover { cursor: pointer; }

Суть идеи в том, что поверх кнопки выводится стандартный input для выбора файла, но он полностью прозрачен и имеет такие же размеры как кнопка. Таким образом, пользователь видит кнопку button, но когда наводит на нее курсор, фактически наводит на input. Соответственно, когда он нажимает на кнопку, на самом деле нажимается input выбора файла. Для того, чтобы не мигал курсор после выбора файла, размер шрифта задан 0px.

Теперь javascript код отправки файла на сервер с отображением прогресса:

$(function() { $("#load_file").on("change", loadfile); }); function loadfile() { $("#addfile span").html("Загружено 0 %"); files = $("#load_file").files; var form = new FormData(); form.append("upload", files); $.ajax({ url: "", type: "POST", data: form, cache: false, processData: false, contentType: false, xhr: function() { var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { myXhr.upload.addEventListener("progress",ShowProgress, false); } return myXhr; }, complete: function(data){ $("#addfile span").html("Загрузить изображение"); $("#load_file").val(""); }, success: function(message){ alert(message); }, error: function(jqXHR, textStatus, errorThrown) { alert(textStatus+" "+errorThrown); } }); } function ShowProgress(e) { if(e.lengthComputable){ $("#addfile span").html("Загружено "+Math.round(100*e.loaded/e.total)+" %"); } }

При загрузке файла на сервер в кнопке будет показываться сколько % уже передано на сервер. После завершения загрузки название кнопки возвращается как было, а значение input-а с файлом устанавливается пустым, чтобы можно было снова выбирать новый файл.

Пример серверной части на php (по просьбе Евгения):

$message = ""; if (empty($_FILES["upload"]["name"]) || $_FILES["upload"] == "none") { $message = "Вы не выбрали файл"; } else if ($_FILES["upload"]["size"] == 0 || $_FILES["upload"]["size"] > 9437184) { $message = "Размер файла не соответствует нормам (максимум 9 Мб)"; } else if (($_FILES["upload"]["type"] != "image/jpeg") && ($_FILES["upload"]["type"] != "image/pjpeg") && ($_FILES["upload"]["type"] != "image/gif") && ($_FILES["upload"]["type"] != "image/png")) { $message = "Допускается загрузка только картинок JPG, GIF и PNG."; } else if (!is_uploaded_file($_FILES["upload"]["tmp_name"])) { $message = "Что-то пошло не так. Попытайтесь загрузить файл ещё раз."; } else { $ftype = $_FILES["upload"]["type"]; $fname = "newname_image.".($ftype == "image/gif" ? "gif" : ($ftype == "image/png" ? "png" : "jpg")); if (move_uploaded_file($_FILES["upload"]["tmp_name"], $_SERVER["DOCUMENT_ROOT"]."/files/".$fname)) { $message = "Изображение успешно загружено."; } else { $message = "Что-то пошло не так. Попытайтесь загрузить файл ещё раз."; } } exit($message);

Информация о загруженном изображении будет содержаться в $_FILES["upload"] , т.к. скриптом файл добавлялся так: form.append("upload", files); Соответственно, всё что требуется от php-программы - это проверить что файл соответствует ожидаемым параметрам, перенести файл в нужную папку (в примере в папку files) под нужным именем (в примере newname_image) и вернуть в браузер ответ, который в моем примере просто выводится пользователю командой alert(message);

Ситуаций, в которых можно и даже нужно использовать ajax-запросы, очень много и все их здесь не разобрать. Тем не менее, если есть предложения, какие еще примеры имеет смысл сюда добавить, пишите в комментариях.

Данную статью начал по просьбам новичков, которые только начинают осваивать JS/jQuery и, рано или поздно, сталкиваются с проблемой, как же на практике использовать технологию Ajax. В этой части, я попробую простым языком (пусть не смущает это пользователей продвинутых ) объяснить, как применить данную "фишку" с использованием библиотеки jQuery в своих проектах.

Итак... В jQuery есть несколько методов, которые осуществляют запросы к серверной части сайта без перезагрузки страницы. Мы не будем рассматривать каждый метод отдельно "под микроскопом", по той простой причине, что все они являются урезанными/сокращенными функция метода $.ajax() . Для начала, давайте помотрим на код ниже, а дальше разберем его подробней:

HTML (файл index.html )

Cool page site

In this file, we have the jQuery library connected, a file with our JS code, a button (id="btn"), by clicking on which an ajax request will be launched, and a block (id="output"), in which we will display the result ajax request work

JS/jQuery ( script.js file)

$(function()( var output = $("#output"); // output block $("#btn").on("click", function()( $.ajax(( url: "path/ to/handler.php", // path to php handler type: "POST", // data transfer method dataType: "json", // type of expected data in response data: (key: 1), // data, which we pass to the server beforeSend: function()( // The function is called before sending the request output.text("Request sent. Please wait for a response."); ), error: function(req, text, error)( // tracking errors during execute an ajax request output.text("Houston, We're in trouble!" + text + " | " + error); ), complete: function()( // function is called when the request ends output.append("

Request completed!

"); ), success: function(json)( // function that will be called in case of successful completion of the request to the server // json is a variable containing the response data from the server. Call it whatever you like;) output.html(json) ; // display the data received from the server on the page ) )); )); ));

I immediately commented this code, so there should not be any special questions. The only thing I want to note for copy-paste lovers is that you need to specify the real path to the handler in the parameter url. And one more thing - in the example we pass the data entered manually (the "key" key with the value "1"), but in real projects, this data is picked up from any sources, but we'll talk about this later.

PHP handler ( handler.php file)

0) $req = "

Got a value equal to: " . $key . "

"; // assign the required data to the variable echo json_encode($req); // return the data as a response, converting it to a JSON string exit; // stop further script execution )

And finally, the PHP handler, in which the request data is processed and a response is formed, which is returned back to be torn apart by our JS code. Everything is extremely simple here. Why are we converting the data to a JSON string - because we specified in the parameter dataType that such data should be expected in the response. And why exactly like this - because this is the most convenient format for further work: you can transfer both a string and an array of data, or immediately prepared HTML code for insertion into a page.

What will happen at each stage:

  1. When the button is clicked, the JS code starts to work
  2. Before sending, the function will work in beforeSend. It will display in the "output" block a message about the beginning of the request
  3. If something goes wrong ( for example, the path to the handler is not correct), then the function will work error and an error will be thrown in the block
  4. If everything is fine, then the function will run success and the result of our request will appear in the block
  5. At the last stage, the function will be executed complete, which will add a message about the end of the AJAX request to the output block

*beforeSend And complete can be used, for example, to display some kind of preloader image to let the user know that the process is in progress. And this is not all the useful options of the method. $.ajax(), but the necessary minimum that will allow the method to function correctly and competently.

And another useful jQuery method that is worthy of attention within this topic - $.ajaxSetup(). If your project will have a lot of Ajax requests, then this method will help you avoid constantly listing the same method settings. $.ajax(). For example, if you have one handler file, use the same data transfer method, receive data in the same format, etc., then this is written once in the method $.ajaxSetup() and in the future, all these settings will be automatically applied to all requests.

// Describe the general settings for all ajax requests $.ajaxSetup(( url: "path/to/handler.php", // path to the php handler type: "POST", // data transfer method dataType: "json" , // type of expected data in the response beforeSend: function()( // The function is called before sending the request output.text("Request sent. Please wait for a response."); ), error: function(req, text, error)( // tracking errors during an ajax request output.text("Houston, We're in trouble! " + text + " | " + error); ), complete: function()( // the function is called when the request ends output.append("

Request completed!

"); ) )); $(function()( var output = $("#output"); $("#btn").on("click", function()( // Now, the entire record of any request , will be reduced // to the data and success parameters: data that we pass // and processing the response from the server $.ajax(( data: (key: 1), // data that we pass to the server success: function(json)( // function that will be called in case of successful completion of the request to the server output.html(json); ) )); )); ));

In the next part, we will consider receiving and passing data using AJAX from forms and other sources, as well as share small useful things that will be useful to you when working on your projects.

AJAX stands for Asynchronous Javascript And XML, which stands for Asynchronous JavaScript and XML. AJAX allows you to update the data of an HTML page 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. The way Google Suggest works is that while you're typing a word or phrase to search, JavaScript accesses the Google database and queries it for the 10 most popular queries that begin with the same letters. And then displays this list without reloading the page.

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

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




<span>Search for offers.</span>
http-equiv="Content-Type" content="text/html; charset=UTF-8">




Rest on the sea

Search offers:


name="country" style="width:250px" autocomplete="off" onkeyup="KeyPress(this.value)" />
type="submit" value="Search" !} />
align="left" id="searchresults">



In this listing, we've created a search form with a text input field and a submit button, and we're creating a div layer to display the results. The 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 reload the html document, we need the 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 the ajax.js file.

/*variable to store the request object*/
varrequest;
/*function to create a request object*/
function CreateRequest()
{
varrequest=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 need to list the results every time you change the search field. To do this, we use a JavaScript event handler. We will determine the changes at each keyboard event keyup . To do this, in our HTML code of the index.html file, in the line where the search field named country is created, add the attribute onkeyup="KeyPress(this.value)" :

name="country" style="width:250px" onkeyup="KeyPress(this.value)" />

That is, when any key is pressed, the KeyPress() JavaScript function will be called, in 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;
  • Form the URL to which you need to connect to get the results;
  • Configure the request object to establish communication with the server;
  • Send a request to the server.

Let's start creating the KeyPress() function. To create a new request object, we just need to set the request variable to the value returned by the CreateRequest() function we created earlier. And to be safe, check the request variable. If it is equal NULL, the request object could not be created. This is what the JavaScript code for this task would look like:

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

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

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

Then we'll set up the connection. To do this, you first need to tell the object where to send this request. Let's generate the URL of the script that will calculate the results and assign it to the url variable. Let's say the php script country.php will be responsible for calculating the results on the server side. Our URL would then look like this: var url = "country.php" + "?s=" + encodeURIComponent(term) + "&sid=" + Math.random(); , where the characters entered in the search field are passed with the variable s, and a random number is assigned to sid 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 the data to the server. We use the method GET, because the characters entered in the search string are passed to the server script via the url. The second parameter specifies the url-address of the server script. We have the url address stored 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 run in asynchronous mode, so we specify true . After the connection is initialized, you need to create the connection and query the results. To do this, you just need to call the send(null) function of the request object. The null parameter indicates that the request contains no data.

After making all the changes, the KeyPress(this.value) function will take the following form:

Function KeyPress(term)
{
/*create a new request object*/
request=CreateRequest();
/* if it was not possible to create the request object, then finish the execution of the function */
if(request==null)
{
return;
}
/*form the url-address*/
var url = "country.php" + "?s=" + encodeURIComponent(term) + "&sid=" + Math.random();
/*configure the request object to establish the connection*/
request.onreadystatechange = LoadResults;
request.open("GET", url, true);
/*send request to 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 get a response, process and display the results on a web page. All this will be handled by the LoadResults() function, which will be called every time the request's readiness status changes. Let's see how this function should work.

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

Function LoadResults()
{


/*process response*/
}
}

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

If the check of the status and status of the request is successful, then you can start processing the data received from the server. There are two ways to get data: 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 output it to the layer with id="searchresults" .

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

Function LoadResults()
{
/*Check the readiness status*/
if (request.readyState == 4)(
/*Check request status*/
if (request.status == 200)(
//make searchresults layer visible
ShowDiv("searchresults");
//clear results
ClearResults();
// get data
var answer = request.responseText;
//convert the text string to an array
vararray = 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;
// loop through all the elements of the array array
for(var i = 0; i (
vartext = array[i];
// create table rows and add to its body
tblRow = document.createElement("tr");
tblCell = document.createElement("td");
//set cell attributes and functions
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 its body to the table
tbl.appendChild(tblbody);
// put the table in the layer
div.appendChild(tbl);
}
}
}

And a couple more JavaScript helper 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 results layer invisible*/
function HideDiv(id)
{
if (document.layers) document.layers.visibility="hide";
else document.getElementById(id).style.visibility="hidden";
}

/*clear results*/
function ClearResults()
{
/* Remove existing rows from result 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 the 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:

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

AJAX is an acronym that stands for Asynchronous Javascript and XML. In fact, AJAX is not a new technology, as both Javascript and XML have been around for quite some time, and AJAX is a synthesis of those technologies. AJAX is most commonly associated with the term Web 2.0 and is touted as the newest Web application.

When using AJAX, there is no need to update the entire page each time, as only a specific part of it is updated. It is much more convenient, since you do not have to wait long, and more economical, since not everyone has unlimited Internet. True, in this case, the developer needs to ensure that the user is aware of what is happening on the page. This can be implemented using loading indicators, text messages that data is being exchanged with the server. You also need to understand that not all browsers support AJAX (old browsers and text browsers). Plus Javascript can be disabled by the user. Therefore, you should not abuse the use of technology and resort to alternative methods of presenting information on the Web site.

Let's summarize the advantages of AJAX:

  • Possibility to create a user-friendly web-interface
  • Active user interaction
  • Ease of use
AJAX uses two methods of working with a web page: changing the web page without reloading it, and dynamically contacting the server. The second can be done in several ways, in particular, XMLHttpRequest, which we will talk about, and using the hidden frame technique.

Data exchange

In order to exchange data, an XMLHttpRequest object must be created on the page, which is a kind of intermediary between the user's browser and the server (Fig. 1). Using XMLHttpRequest, you can send a request to the server, as well as receive a response in the form of various kinds of data.

There are two ways to exchange data with the server. The first way is a GET request. In this request, you are accessing a document on the server, passing arguments to it via the URL itself. At the same time, on the client side, it will be logical to use the Javascript escape function so that some data does not interrupt the request.

The client part, written in Javascript, must provide the necessary functionality for secure communication with the server and provide methods for exchanging data in any of the above ways. The server part must process the input data, and based on them generate new information (for example, working with the database), and give it back to the client. For example, to request information from the server, you can use a regular GET request with the transfer of several and small parameters, and to update information or add new information, you will need to use a POST request, since it allows you to transfer large amounts of data.

As already mentioned, AJAX uses asynchronous data transfer. This means that while the data is being transferred, the user can perform other actions he needs. At this time, the user should be notified that some kind of data exchange is taking place, otherwise the user will think that something wrong has happened and can leave the site, or re-call the function that “hung”, in his opinion. Indication during communication in a Web 2.0 application plays a very important role: visitors may not yet be used to these ways of refreshing the page.

The response from the server can be not only XML, as the name of the technology implies. In addition to XML, you can get a response in the form of plain text, or JSON (Javascript Object Notation). If the response was received in plain text, then it can be immediately displayed in a container on the page. When an XML response is received, the resulting XML document is typically processed on the client side and converted to (X)HTML. When receiving a JSON response, the client only needs to execute the received code (Javascript's eval function) to obtain a full-fledged Javascript object. But here you need to be careful and take into account the fact that malicious code can be transferred using this technology, so before executing the code received from the server, it should be carefully checked and processed. There is such a practice as an "idle" request, in which no response comes from the server, only the data on the server side is changed.

In different browsers, this object has different properties, but in general it is the same.

XMLHttpRequest Object Methods

Note that the method names are written in the same style (Camel-style) as other Javascript functions. Be careful when using them.

abortion()- cancel the current request to the server.

getAllResponseHeaders()- get all response headers from the server.

getResponseHeader("header_name")- get the specified title.

open("request_type","URL","asynchronous","username","password")- initialization of the request to the server, specifying the request method. Request type and URL are required parameters. The third argument is a boolean value. Usually always set to true or not set at all (default is true). The fourth and fifth arguments are used for authentication (it's very insecure to store the authentication data in the script, since the script can be viewed by any user).

send("content")- send an HTTP request to the server and get a response.

setRequestHeader("header_name","value")- set request header values.

Properties of the XMLHttpRequest object

onreadystatechange is one of the most important properties of the XMLHttpRequest object. With the help of this property, a handler is set, which is called whenever the object's status changes.

readyState- a number indicating the status of the object.

responseText- representation of the server response in the form of plain text (string).

responseXML- a document object compatible with the DOM received from the server.

status- status of the response from the server.

statusText- textual representation of the status of the response from the server.

Let's take a closer look at the readyState property:

  • 0 - The object is not initialized.
  • 1 - The object is loading data.
  • 2 - The object has loaded its data.
  • 3 - The object is not fully loaded, but can be interacted with by the user.
  • 4 - The object is fully initialized; received a response from the server.
It is based on the state of readiness of the object that you can provide the visitor with information about the stage of the data exchange with the server and, possibly, notify him of this visually.

Creating an XMLHttpRequest Object

As mentioned above, creating this object for each type of browser is a unique process.

For example, to create an object in Gecko-compatible browsers, Konqueror and Safari, you would use the following expression:

VarRequest = new XMLHttpRequest();

And for Internet Explorer, the following is used:

VarRequest = new ActiveXObject("Microsoft.XMLHTTP");

Var Request = new ActiveXObject("Msxml2.XMLHTTP");

Now, in order to achieve cross-browser compatibility, you need to add all the functions into one:

Function CreateRequest() ( var Request = false; if (window.XMLHttpRequest) ( //Gecko compatible browsers, Safari, Konqueror Request = new XMLHttpRequest(); ) else if (window.ActiveXObject) ( //Internet explorer try ( Request = new ActiveXObject("Microsoft.XMLHTTP"); ) catch (CatchException) ( Request = new ActiveXObject("Msxml2.XMLHTTP"); ) ) if (!Request) ( alert("Unable to create XMLHttpRequest"); ) return Request; )

After all this, you can create this object and not worry about performance on popular browsers. But you can create an object in different places. If you create it globally, then at a certain point in time only one request to the server will be possible. You can create an object every time a request is made to the server (this will almost completely solve the problem).

Server request

The server request algorithm looks like this:

  • Checking for the existence of XMLHttpRequest.
  • Initializing the connection to the server.
  • Sending a request to the server.
  • Processing of received data.
To create a request to the server, we will create a small function that will combine the functionality for GET and POST requests.

/* Function for sending a request to a file on the server r_method - request type: GET or POST r_path - path to the file r_args - arguments like a=1&b=2&c=3... r_handler - function to handle the response from the server */ function SendRequest(r_method , r_path, r_args, r_handler) ( //Create a request var Request = CreateRequest(); //Check if the request exists again if (!Request) ( return; ) //Assign a custom handler Request.onreadystatechange = function() ( // If the data exchange is complete if (Request.readyState == 4) ( //Give control to the user handler r_handler(Request); ) ) //Check if a GET request is required if (r_method.toLowerCase() == "get" && r_args.length > 0) r_path += "?" + r_args; //Initialize the connection Request.open(r_method, r_path, true); if (r_method.toLowerCase() == "post") ( //If this is a POST- request //Set header Request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8"); //Send request Request.send(r_args); ) else ( //If this is a GET request //Send a null request Request.send(null); ) )

Creating a request has become much easier. For example, let's write a function that will receive the contents of a file on the server and output it to a container.

Function ReadFile(filename, container) ( //Create a handler function var Handler = function(Request) ( document.getElementById(container).innerHTML = Request.responseText; ) //Send the request SendRequest("GET",filename,"", Handler); )

This is how the interaction with the server takes place.

Response processing

In the previous example, we made a request function to the server. But it is, in fact, insecure, since we do not process the state of the object and the state of the response from the server.

Let's add to our code so that it can display a visual notification about the loading process.

Request.onreadystatechange = function() ( //If the data exchange is completed if (Request.readyState == 4) ( //Give control to the user handler r_handler(Request); ) else ( //Notify the user about the download ) ) ...

As you already know, the XMLHttpRequest object lets you know the status of the response from the server. Let's take advantage of this opportunity.

Request.onreadystatechange = function() ( //If the data exchange is completed if (Request.readyState == 4) ( if (Request.status == 200) ( //Transfer control to the user handler r_handler(Request); ) else ( // Notify the user about an error that has occurred ) ) else ( //Notify the user about the download ) ) ...

Server response options

Several types of data can be received from the server:

  • plain text
If you receive plain text, then you can immediately send it to the container, that is, to the output. When receiving data as XML, you must process the data using DOM functions and render the result using HTML.

JSON is Javascript object notation. With its help, you can represent an object as a string (here you can draw an analogy with the serialization function). When receiving JSON data, you must execute it in order to obtain a full-fledged Javascript object and perform the necessary operations on it. Please be aware that such data transmission and execution are not secure. You have to keep track of what goes into execution.

JSON code example:
( "data": ( "misc": [ ( "name" : "JSON element one", "type" : "Subheading 1" ), ( "name" : "JSON element two", "type" : " Subtitle 2" ) ] ) )

Upon receipt of such a code, we perform the following action:

var responsedata = eval("(" + Request.responseText + ")")

After executing this code, the object will be available to you responsedata.

Working with server-side programming languages

Such work is no different from the usual. For examples, I'll take PHP as the server-side language. Nothing has changed on the client side, but the server side is now represented by a PHP file.

By tradition, let's start with a greeting to our wonderful world:

echo "Hello, World!";

When accessing this file, the string Hello, World will be returned to the client. As you understand, this represents the broadest possibilities for building applications. By passing arguments when calling the server with XMLHttpRequest, you can parameterize the output, thereby providing rich functionality to the Web application.

Apart from PHP, any other server-side programming language can be used.