-
Notifications
You must be signed in to change notification settings - Fork 5
forms ajax
David Spreekmeester edited this page Dec 2, 2014
·
1 revision
Make sure the "ajax" class is on the form. The easiest way is to use the setAjax()
method:
<?php
$form->setAjax(true);
?>
The form will be hijacked (code for this is found in garp.front.js
) and an XMLHttpRequest will be made to the action of the form, using the method of the form.
In the controller, the easiest way to handle an AJAX call is like this:
<?php
if ($this->getRequest()->isPost()) {
// Do your usual form processing here.
// This also acts as proper fallback code for
// the poor folks without Javascript
$this->view->valid = true;
if ($this->getRequest()->isXmlHttpRequest()) {
$this->_helper->layout->setLayoutPath(
GARP_APPLICATION_PATH . '/modules/g/views/layouts'
);
$this->_helper->layout->setLayout('form_json_response');
}
}
?>
This will take the HTML from the view of your controller actions (e.g. views/forms/submit.phtml
). Your response HTML will be rendered in a JSON wrapper looking like this:
<?php
{
"success": 1,
"html": "<p>Thanks for registering!</p>"
}
?>
The HTML is what is rendered in your view. Make sure it can be used in place of the form itself, because the hijacking code will do exactly that: replace the form with whatever's in "html".