- Ajax-запросы нативными средствами Joomla
- Ajax в Joomla — Joomla.request
- Joomla 3
- Выбор метода запроса (POST или GET)
- Проверка CSRF-токена в точке входа
- Установка заголовков ajax-запроса
- Отправка данных через ajax в Joomla
- Callback-функции ajax-запроса в Joomla
- Флаг perform
- Joomla 4
- Developing an MVC Component/Adding AJAX
- Материал из Joomla! Documentation
- Содержание
- Functionality [ править ]
- Approach [ править ]
- Initiating the Ajax Request [ править ]
- Handling the Ajax Request [ править ]
- Handling the Ajax Response [ править ]
- Error Handling [ править ]
- Site Helloworld Page [ править ]
- Javascript Code [ править ]
- Server Code [ править ]
- Updated Language Strings [ править ]
- Packaging the Component [ править ]
- J3.x:Developing an MVC Component/Adding AJAX
- Материал из Joomla! Documentation
- Содержание
- Functionality
- Approach
- Initiating the Ajax Request
- Handling the Ajax Request
- Handling the Ajax Response
- Error Handling
- Site Helloworld Page
- Javascript Code
- Server Code
- Updated Language Strings
- Packaging the Component
- AJAX функциональность с помощью AJAX интерфейса com_ajax
- Постановка задачи
- Подготавливаем макеты вывода
- Добавляем AJAX запрос
- Добавляем AJAX обработчик
- Код модуля
Ajax-запросы нативными средствами Joomla
Небольшая заметка о том, как делать ajax-запросы штатными средствами без использования дополнительных js-библиотек (jQuery, etc). Joomla 3 и Joomla 4 предоставляют небольшую обёртку для конструирования XMLHttpRequest. В целом синтаксис очень похож на тот же jQuery Ajax, поэтому заменить его будет очень легко.
В страницы можно увидеть core.js, в котором есть немало любопытных функций для работы с фронтом на Joomla. Об одной из них (получение данных из php в js) писалось здесь: Разработка форм обратной связи для магазинов на Joomla 3. Для создания ajax-запросов нам пригодится Joomla.request.
Ajax в Joomla — Joomla.request
Joomla 3
Представим, что Вам нужно просто отправить запрос, не получая никаких данных:
Выбор метода запроса (POST или GET)
Если выбран метод запроса POST. то автоматически будет отправляться заголовок X-CSRF-Token и сам CSRF-токен, который можно и нужно проверить в точке входа.
Проверка CSRF-токена в точке входа
Для этого используем метод Session::checkToken. В качестве параметра можно указывать как post (это значение по умолчанию), так и get.
Проверить наличие CSRF-токена на странице можно в консоли браузера:
Joomla.getOptions в консоли браузера
Если CSRF-токена в Joomla Script options нет, то в PHP можно его добавить с помощью класса HTMLHelper.
Установка заголовков ajax-запроса
Есть возможность установки своих заголовков ajax-запроса. Например, заголовка Cache-Control, тогда будет корректно работать условная ajax-корзина, каждый раз получая свежие данные. Также можно устанавливать свои уникальные заголовки, если это необходимо.
Отправка данных через ajax в Joomla
Отправка данных на выбранный url происходит согласно спецификации. Чаще всего это или строка или объект. Для того, чтобы данные пришли в удобном виде стоит применить к передаваемому объекту JSON.stringify, так же указать заголовок запроса Content-type:applictation/json. Хорошая статья о FormData на learn.javascript.ru в помощь.
Если метод запроса POST, в data передается просто строка и не установлен заголовок Content-Type, то он (Content-Type) принимает значение application/x-www-form-urlencoded. В php получаем данные следующим образом:
Callback-функции ajax-запроса в Joomla
onBefore: function(xhr)<> — выполняется перед запросом. Запрос не выполнится, если данный callback вернёт false.
onSuccess: function(response, xhr)<> — выполняется после успешного завершения запроса. response — это xhr.responseText,
onError: function(xhr)<> — выполняется после неудачного запроса.
Запрос обёрнут в try-catch, поэтому если запрос не проходит — смотрим в консоль, там должна логироваться ошибка.
Флаг perform
Это значение по умолчанию установлено в true. Если установить в false — запрос не будет выполняться, а так же не будет вызываться callback-функция onBefore. Полезно в тех случаях, когда не нужно в процессе разработки некоторое время дёргать лишний раз сервер.
Joomla 4
В Joomla 4 метод переписан, но для простых смертных всё остается так же. Добавляется лишь ещё одна callback-функция onComplete, которая выполняется в любом случае — как после успешного запроса, так и в случае ошибки.
Приветствую аргументированные замечания и пожелания к заметке.
Developing an MVC Component/Adding AJAX
Материал из Joomla! Documentation
Articles in this Series
This is a multiple-article series of tutorials on how to develop a Model-View-Controller Component for Joomla! Version .
Begin with the Introduction, and navigate the articles in this series by using the navigation button at the bottom or the box to the right (the Articles in this series).
This tutorial is part of the Developing a MVC Component for Joomla! 3.x tutorial. You are encouraged to read the previous parts of the tutorial before reading this. This step introduces how to use AJAX within a Joomla component.
A video accompanying this step can be found at step 19 adding ajax (although the video was recorded before some of the language strings were properly coded).
Содержание
Functionality [ править ]
In the previous step we added a map to our site web page. In this step we extend this to provide a «Search Here» facility for the map.
On our site page we’ll display a «Search Here» button, and when the user clicks this the javascript will make an Ajax call to the server to retrieve those Helloworld records which have latitude and longitude values which fall within the bounds of the map, as it’s currently displayed on the page.
We’ll then display the results of that search in a series of rows under the map.
Approach [ править ]
Initiating the Ajax Request [ править ]
On our Search Here button we’ll put an onclick listener, and in that javascript function we’ll initiate the Ajax call. We’ll use the jQuery library call for the Ajax request, as that makes it all fairly straightforward.
We’ll need to get the bounds of the map in lat/long format, and include that in our Ajax request to the server. We’ll also set a task= parameter to call a specific controller function, to keep our Ajax-handling code separate. And we’ll also indicate that we expect the result returned to be in JSON format.
As security is as important here as always, we’ll include a form token on the site web page which we’ll also send in the Ajax request.
Handling the Ajax Request [ править ]
On the server we’ll extend our Joomla PHP code and structure it according to the MVC pattern:
- In our existing controller we’ll add a new function, whose main purpose will be to check the security token
- We will have a new view file which will contain the main logic for pulling together the JSON response
- We will extend our existing model to handle the SQL query for finding the records whose lat/long values fit within the lat/long bounds of the map.
Handling the Ajax Response [ править ]
Back in our Javascript code we’ll interpret the resulting JSON returned, and output the records in some HTML below the map.
Error Handling [ править ]
A significant part of our code will be associated with handling the various errors which may occur. We’ll use the Joomla JResponseJson class to help both with forming the JSON response and in handling the various error scenarios. It’s worth reading the good description of this functionality at JSON Responses with JResponseJson.
Site Helloworld Page [ править ]
We add 3 fields within a new div section below the map:
- A Search Here button, styled using Bootstrap, and with an onclick listener
- A Joomla form token
- A subsidiary div which is the area where we will output the search results
Javascript Code [ править ]
Into our javascript code we’ll add 3 functions:
- the onclick listener which will initiate the Ajax call
- a function to get the bounds of the map in lat/long format
- a function to display the results
If you’re using Google Maps instead of Openlayers to display the map, then the way to find the map bounds is described in this stackoverflow question.
Server Code [ править ]
Into our main site controller we include the checking of the token. If it passes we call the standard controller display() function.
The standard display() function sets up the model and the view, and then calls the display() function of the view. However, because we’ve included format=json as a parameter in our Ajax HTTP request, Joomla will look for this function in a view.json.php file instead of the usual view.html.php file. So we put our view code into this new file.
Finally we include our getMapSearchResults function in our existing model.
Updated Language Strings [ править ]
Packaging the Component [ править ]
Contents of your code directory. Each file link below takes you to the step in the tutorial which has the latest version of that source code file.
J3.x:Developing an MVC Component/Adding AJAX
Материал из Joomla! Documentation
Articles in this Series
This is a multiple-article series of tutorials on how to develop a Model-View-Controller Component for Joomla! Version .
Begin with the Introduction, and navigate the articles in this series by using the navigation button at the bottom or the box to the right (the Articles in this series).
This tutorial is part of the Developing a MVC Component for Joomla! 3.x tutorial. You are encouraged to read the previous parts of the tutorial before reading this. This step introduces how to use AJAX within a Joomla component.
A video accompanying this step can be found at step 19 adding ajax (although the video was recorded before some of the language strings were properly coded).
Содержание
Functionality
In the previous step we added a map to our site web page. In this step we extend this to provide a «Search Here» facility for the map.
On our site page we’ll display a «Search Here» button, and when the user clicks this the javascript will make an Ajax call to the server to retrieve those Helloworld records which have latitude and longitude values which fall within the bounds of the map, as it’s currently displayed on the page.
We’ll then display the results of that search in a series of rows under the map.
Approach
Initiating the Ajax Request
On our Search Here button we’ll put an onclick listener, and in that javascript function we’ll initiate the Ajax call. We’ll use the jQuery library call for the Ajax request, as that makes it all fairly straightforward.
We’ll need to get the bounds of the map in lat/long format, and include that in our Ajax request to the server. We’ll also set a task= parameter to call a specific controller function, to keep our Ajax-handling code separate. And we’ll also indicate that we expect the result returned to be in JSON format.
As security is as important here as always, we’ll include a form token on the site web page which we’ll also send in the Ajax request.
Handling the Ajax Request
On the server we’ll extend our Joomla PHP code and structure it according to the MVC pattern:
- In our existing controller we’ll add a new function, whose main purpose will be to check the security token
- We will have a new view file which will contain the main logic for pulling together the JSON response
- We will extend our existing model to handle the SQL query for finding the records whose lat/long values fit within the lat/long bounds of the map.
Handling the Ajax Response
Back in our Javascript code we’ll interpret the resulting JSON returned, and output the records in some HTML below the map.
Error Handling
A significant part of our code will be associated with handling the various errors which may occur. We’ll use the Joomla JResponseJson class to help both with forming the JSON response and in handling the various error scenarios. It’s worth reading the good description of this functionality at JSON Responses with JResponseJson.
Site Helloworld Page
We add 3 fields within a new div section below the map:
- A Search Here button, styled using Bootstrap, and with an onclick listener
- A Joomla form token
- A subsidiary div which is the area where we will output the search results
Javascript Code
Into our javascript code we’ll add 3 functions:
- the onclick listener which will initiate the Ajax call
- a function to get the bounds of the map in lat/long format
- a function to display the results
If you’re using Google Maps instead of Openlayers to display the map, then the way to find the map bounds is described in this stackoverflow question.
Server Code
Into our main site controller we include the checking of the token. If it passes we call the standard controller display() function.
The standard display() function sets up the model and the view, and then calls the display() function of the view. However, because we’ve included format=json as a parameter in our Ajax HTTP request, Joomla will look for this function in a view.json.php file instead of the usual view.html.php file. So we put our view code into this new file.
Finally we include our getMapSearchResults function in our existing model.
Updated Language Strings
Packaging the Component
Contents of your code directory. Each file link below takes you to the step in the tutorial which has the latest version of that source code file.
AJAX функциональность с помощью AJAX интерфейса com_ajax
Сразу хочу обратить ваше внимание на то, что этот материал относится к Joomla 3.2+, так как именно в этой версии появился удобный AJAX интерфейс в виде компонента com_ajax . Компонент является точкой входа для AJAX запросов в модули и плагины.
Постановка задачи
Итак, наш модуль выводит список последних зарегистрированных пользователей. Чтобы показать, как легко можно реализовать AJAX функциональность в модуле, в качестве примера сделаем следующее – при клике на пользователя будут отображаться заголовки последних трех материалов пользователя.
Конечно, это очень надуманный пример, так как статьи можно было бы с легкостью получить сразу же со списком пользователей. Но наша главная задача состоит в том, чтобы разобраться, как работает AJAX интерфейс, поэтому суть примера в принципе не важна.
Подготавливаем макеты вывода
В макетах нам нужно предусмотреть вывод ID пользователя, чтобы затем передать его в AJAX запрос. Также нам нужно добавить контейнер для вывода списка материалови обернуть вывод пользователя в ссылку, чтобы привязаться к событию клика.
Наш модуль имеет два макета: default и table . В качестве примера возьмем default макет. Все изменения в разметке были сделаны между тегами
:
Добавляем AJAX запрос
Для составления AJAX запроса в модуле мы должны придерживаться определенных правил, которые диктует нам интерфейс компонента com_ajax . Следующие параметры являются обязательными при формировании запроса:
- option=com_ajax – всегда используем компонент com_ajax ;
- module=module_name – передаем имя модуля, в который мы делаем запрос. Важный момент – имя модуля должно быть без префикса mod_ ;
- format=json – указываем формат возвращаемых данных: raw , json или debug .
Код AJAX запроса мы добавляем в конце точки входа модуля mod_latest_users.php :
Совет. Используйте в качестве возвращаемых данных формат json . В таком случае com_ajax использует класс JResponseJson, который очень удобен в плане обработки возвращенных данных. Подробнее об этом классе вы можете прочитать в материале JResponseJson – возвращаем данные в формате JSON.
Не забудьте добавить в языковые файлы константы:
Добавляем AJAX обработчик
Поддержка модулей в AJAX интерфейсе реализована через вызов метода в файле хелпера модуля, название которого должно заканчиваться на Ajax . По умолчанию префиксом метода является get , в итоге мы получаем getAjax() .
Мы можем вызвать метод с другим именем, задав имя метода в переменной method при формировании запроса, например method=myMethod . Таким образом, будет вызван метод myMethodAjax() . Это дает возможность реализовать в модуле несколько различных обработчиков AJAX запросов.
Вот как выглядит обработчик в нашем модуле:
В принципе, метод достаточно прост и не требует особых комментариев. Единственное, можно отметить, что ID пользователя мы получаем из запроса с помощью JInput.
На примере этого материала мы с вами убедились в том, что добавление AJAX в модуль Joomla является довольно простой задачей благодаря AJAX интерфейсу. Удачной вам разработки!
Код модуля
Исходный код модуля доступен на GitHub: для Joomla 2.5 и для Joomla 3.
Также вы можете скачать архив: для Joomla 2.5 и для Joomla 3.