I am working on Zend and my objective is to get the returned content of a form with AJAX (so that I don't have to reload all the page).
Here is what I have :
ZendForm -> FormController -> View
On the FormController, I check if there is a post :
if(isPost) {$this->sendJson($data);}
else {return $From;}
In my view i display the form with a echo $this->smartForm($Form);
My problem is on the view I couldn't figure out how to use AJAX to dump the array without reloading the page.
My Form View and controller are working fine, my issue is only on the method. If someone could give me a snap of a code or an example that would be great.
Thank you
You've not tagged jQuery, so I'm giving you a JavaScript only answer.
Read this on sending Forms from Mozzila
Here's an answer on sending a simple form using just Javascript. Code below is from that answer.
const form = document.querySelector("#debarcode-form");
form.addEventListener("submit", e => {
e.preventDefault();
const fd = new FormData(form);
const xhr = new XMLHttpRequest();
xhr.addEventListener("load", e => {
console.log(e.target.responseText);
});
xhr.addEventListener("error", e => {
console.log(e);
});
xhr.open("POST", form.action);
xhr.send(fd);
});
Make sure that the form you've rendered in the PHTML partial via ZF2 contains the correct action URL (so you've used the URL ViewHelper like so: <?= $this->url('name/of/path') ?>
). This is to make sure that the JavaScript sends the data to the correct spot of your Zend Framework application.
Next, handle the data like so in your Controller:
public function handleFormAction()
{
/** @var \Zend\Http\Request $request */
$request = $this->getRequest();
/** @var \Some\Namespace\Of\CustomForm $form */
$form = $this->getCustomForm(); // You've created this using a Factory of course
if ($request->isPost()) {
$form->setData(\Zend\Json\Json::decode($request->getContent(), Json::TYPE_ARRAY));
if ($form->isValid()) {
$object = $form->getObject();
// object handling, such as saving
// Success response
// Redirect to success page or something
$this->redirect()->toRoute('success/route/name', ['id' => $object->getId()]);
}
// Fail response, validation failed, let default below handle it ;-)
}
if ($request->isXmlHttpRequest()) {
return new \Zend\View\Model\JsonModel([
'form' => $form,
'validationMessages' => $form->getMessages() ?: '',
]);
}
// Default response (GET request / initial page load (not async) )
return [
'form' => $form,
'validationMessages' => $form->getMessages() ?: '',
];
}
This answer obviously misses stuff, such as creating the Form for the Controller using a Factory, routing configurations and object hydration and handling.
This is because these things are out of scope of the question.
P.S. - I've used FQCN's (Fully Qualified Class Name), you should include them at the top of the file.