Valider formulaire Zend avec Ajax
Bonjour, j'ai créé un formulaire Zend et je souhaiterais valider celui-ci avec l'aide de l'Ajax.
Pour faire cela, j'ai d'abord précisé dans ma méthode init de mon contrôleur, les actions qui sont susceptibles d'utiliser de l'Ajax en faisant ceci:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('index', 'html')
->addActionContext('add', array('html', 'json'))
->initContext();
if ($this->_request->isXmlHttpRequest())
{
$this->_helper->layout->disableLayout();
}
} |
Dans mon formulaire, j'ai rajouté un attribut onclick à mon bouton submit qui appel une fonction javascript:
Code:
1 2 3 4 5
|
$send = new Zend_Form_Element_Submit('send');
$send->setLabel('Envoyer')
->setAttrib('id', 'send')
->setAttrib('onclick', 'return submitForm();'); |
Voici ce que fait ma méthode javascript appellée:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
function submitForm()
{
alert("coucou");
$.ajax(
{
url: 'index/add',
type: "POST",
context: document.ajax,
data: {
"format" : "html",
"nom" : document.getElementById("nom").value,
"prenom" : document.getElementById("prenom").value
},
error: errorAjax,
dataType: "text",
success: function(data)
{
$("#ajax").html(data);
}
});
} |
Et je récupère bien entendu tout ceci dans mon action appelée qui est add():
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
public function addAction()
{
$form = new Application_Form_User();
if ($this->_request->isXmlHttpRequest())
{
if($this->getRequest()->isPost())
{
// si contexte JSON
/*if($this->ajaxContext->getCurrentContext() == 'json')
{
$this->view->result = $form->processAjax($this->request->getPost());
}*/
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData))
{
$tableau = array();
$tableau["nom"] = $this->_getParam("nom");
$tableau["prenom"] = $this->_getParam("prenom");
$user = new Application_Model_DbTable_Users;
$user->addUser($tableau);
}else
{
$form->populate($formData);
}
}
}
$this->view->form = $form;
} |
Le problème dans tout ceci est quand je clique sur mon bouton submit de mon formulaire, j'ai bien ma popup avec "coucou" qui apparaît et c'est tout, puis ma page se rafraîchit alors qu'elle ne devrait pas mais je ne sais pas pourquoi.. :/
Comment ca se fait svp?