AJAX is used increasingly when rendering page content and for processing forms. The recommended process in front-end MODX is to use a resource as the controller. So, when building sites I normally create a series of resources, each with a single call to a snippet. I can then link to the appropriate resource in my AJAX JS and it will fire the snippet.
BUT, if you have the need for calls to lots of different AJAX functions then you can end up with lots of resources each with just a single call to a snippet. It's annoying from a resource tree point of view and seems a waste of time.
I couldn't find a definitive solution for the front-end, so I worked out a way that uses a single resource to call an 'AJAX connector' snippet that then routes to the appropriate 'AJAX action' snippet.
1. Create an uncached resource called 'ajax-connector' with just the following call:
2. Create a snippet called 'ajaxConnector':
<?php
//This connector runs the action snippet specified in the resource querystring
$output = '';
if ($_GET['action'] != '') {
$output = $modx->runSnippet($_GET['action'],$_GET);
}
else {
$output = 'failed';
}
return $output;
3. Create your specific action snippet - let's call it 'ajaxAction':
<?php
// do whatever you want to run in the ajax session
echo $message;
return;
4. Then use the following URL structure in your AJAX JS call, e.g:
$('#div').load('[[++site_url]]ajax-connector?action=ajaxAction&message=It%20worked');
You could also make step 3 (actionSnippet) a static snippet to allow version control and external file editing.
I'm by no means an expert so there may be some glaring security/caching issues in play here. So please feel free to comment/edit. There may also be a more official way of doing this - if that's so, please someone tell me, quick!