php - Display Zend Form Validation error in Ajax -
there zend registration form. having input username, email, password , confirm password. validator email following:
$this->add(array( 'name' => 'email_reg', 'required' => true, 'filters' => array( array( 'name' => 'striptags', ), array( 'name' => 'stringtrim', ), ), 'validators' => array( array( 'name' => 'emailaddress', 'options' => array( 'domain' => true, 'messages' => array( \zend\validator\emailaddress::invalid_format => 'email address format invalid' ), ), ), array( 'name' => 'db\norecordexists', 'options' => array( 'table' => 'user', 'field' => 'email', 'adapter' => $sm->get ( 'zend\db\adapter\adapter' ), 'messages' => array( norecordexists::error_record_found => 'e-mail address exists' ), ), ), ), )); there 4 validators: required type, e-amil format , if there following e-mail in database. error messages be: - e-mail required - email address format invalid - e-mail address exists
problem trying catch error messages , output using ajax. in registercontroller having following function:
public function ajaxaction() { if (!$this->request->ispost()) { return $this->redirect()->toroute(null, array( 'controller' => 'index' ) ); } $form = $this->getservicelocator()->get('registerform'); $form->setinputfilter(new registerfilter($this->getservicelocator())); $post = $this->request->getpost(); $form->setdata($post); $response = $this->getresponse(); $hello = 1; if (!$form->isvalid()){ // email invalid; print reasons $json= $form->getmessages(); $response->setcontent(\zend\json\json::encode($json)); } return $response; } and jquery file:
$( document ).ready(function() { var urlform = "register/ajax"; $("#btnregister").click( function() { $("#register").submit( function() { return false; }); $.ajax({ url: urlform, type: 'post', datatype: 'json', async: true, data: $(".form-signin").serialize(), success: function (data) { $("#rcheck").text(data); console.log(data); }, error: function (data) { $("#rcheck").text(data); console.log(data); } }); }); }); in console got https://imagizer.imageshack.us/v2/558x205q90/661/uc09da.png , in div id #rcheck getting [object][object].
from image provided error messages correctly returned. error trying write directly object div.
you should have seached how read object javascript. try code :
success: function (data) { data.foreach(function(datum) { object.keys(datum).foreach(function (key) { $('<p>'+obj[key]+'</p>').appendto('#rcheck'); }); }); console.log(data); }, or may within ajaxaction :
$messages = array(); $errors = $form->getmessages(); foreach($errors $key=>$row) { if (!empty($row) && $key != 'submit') { foreach($row $keyer => $rower) { $messages[$key][] = $rower; } } } if (!empty($messages)){ $response->setcontent(\zend\json\json::encode($messages)); } return $response; here's post on how use zend\form ajax validation.
hope help.
Comments
Post a Comment