Very easy way to handle ajax requests in MODx Revolution
- From the sandbox
- Tutorial
In turn, I want to offer another, very simple way to handle ajax requests in MODx Revolution.
First, create a plugin called ajaxReqeust, with the following contents:
event->name == 'OnLoadWebDocument') {
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$modx->resource->set('cacheable', 0);
$modx->resource->set('template', 0);
}
}
The plugin should fire on the OnLoadWebDocument system event.
This plugin will allow us to perform ajax requests to resources and receive only content in response, without a template.
All that is required of us is to save the desired snippet or chunk to the content of the resource.
As an example, consider the process of processing a form submitted via an ajax request.
Create a new resource with any data, in the content field, enter the standard call of the FormIt snippet :
Форма обратной связи
[[!request? &k=`success` &toPlaceholder=`success`]]
[[+success:is=``:then=`
[[!FormIt?
&hooks=`email,redirect`
&redirectTo=`[[*id]]`
&redirectParams=`{"success":"1"}`
&emailTpl=`feedbackEmailTpl`
&emailSubject=`Новый вопрос с сайта [[++site_name]]`
&emailTo=`[email protected]`
&emailFrom=`[email protected]`
&emailFromName=`[[++site_name]]`
&validate=`
name:required:stripTags,
email:email:required,
message:required:stripTags
`
&clearFieldsOnSuccess=`1`
&validationErrorMessage=`Возникли ошибки при отправке сообщения.`
]]
`:else=`
Ваше сообщение успешно отправлено.
`]]
Let's create a small snippet called request, which will allow us to display a message if the form is successfully submitted:
toPlaceholder($toPlaceholder, $result);
}
else {
return $result;
}
All that remains for us to do is to connect a small jQuery code to the page on which the form will be displayed.
This script submits the form via an ajax request and processes the received response:
$(document).ready(function() {
$('body').on('submit', '.ajax-form', function(e) {
e.preventDefault();
var target = this;
if ($(this).data('target') != undefined) {
target = $(this).data('target');
}
values = $(this).serializeArray();
$(this).find('input[type="submit"]').attr('disabled', 'disabled');
$.ajax({
type: 'POST',
dataType: 'html',
url: $(this).attr('action'),
data: values,
success: function(data) {
$(target).replaceWith(data);
}
});
});
});
That's probably all, just isn't it?
You do not need to do anything else, any additional scripts, connectors and processors, just one small plug-in, and MODx will take care of the rest.
Chunks and snippets will be processed in the same way as with regular requests, that is, no hacks are needed to process MODx tags, the answer comes already processed by the parser.
That's all, I hope my little article will make life a little easier for someone.
Good luck to everyone and see you soon.