Created
March 16, 2015 23:13
-
-
Save juliangorge/c818d64ccb7fb5bc15ea to your computer and use it in GitHub Desktop.
ZF2 & DoctrineModule: Submitting a form with AJAX.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
public function createAction() | |
{ | |
$objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); | |
$form = new \Admin\Form\RegisterForm($objectManager); | |
$register = new \Admin\Entity\Register(); | |
$form->bind($register); | |
$viewmodel = new ViewModel(); | |
$viewmodel->setTerminal($this->getRequest()->isXmlHttpRequest()); | |
$viewmodel->setVariables(array('form' => $form)); | |
return $viewmodel; | |
} | |
public function saveAction() | |
{ | |
$objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); | |
$form = new \Admin\Form\RegisterForm($objectManager); | |
$register = new \Admin\Entity\Register(); | |
$form->bind($register); | |
if($this->getRequest()->isXmlHttpRequest()){ | |
if($this->getRequest()->isPost()){ | |
$form->setData($this->getRequest()->getPost()); | |
$hello = 0; | |
if($form->isValid()){ | |
$hello = 1; | |
$objectManager->persist($register); | |
$objectManager->flush(); | |
}else{ | |
foreach($form->getMessages() as $key=>$row) | |
if(!empty($row) && $key != 'submit') | |
foreach($row as $keyer => $rower) | |
$messages[$key][] = $rower; | |
} | |
if(!empty($messages)) | |
$this->getResponse()->setContent(\Zend\Json\Json::encode($messages)); | |
else | |
$this->getResponse()->setContent(\Zend\Json\Json::encode(array('hello' => $hello))); | |
} | |
return $this->getResponse(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
var urlform = "<?php echo $this->url('register/default', array('action' => 'save')) ?>"; | |
$(document).ready(function() { | |
// process the form | |
$('form').submit(function(event) { | |
$.ajax({ | |
type : 'POST', | |
url : urlform, | |
data : $('form').serialize(), | |
dataType : 'json', | |
encode : true | |
}) | |
.done(function(data) { | |
console.log(data); | |
}) | |
.fail(function(data) { | |
console.log('Error che: '); | |
console.log(data); | |
}); | |
event.preventDefault(); | |
}); | |
}); | |
</script> | |
<!--Add you form--> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment