Welcome Guest, Not a member yet? Register   Sign In
How To Retrieve Form Validation errors?
#1

[eluser]Stephane02[/eluser]
Hi,

I'm writing a function to handle ajax request and I'm using CI form validation
class to validate inputs. How should I retrieve validation errors as I want to output them
in a die() function.

Stephane
#2

[eluser]pickupman[/eluser]
I don't think there is really any need for a die() in CI. What you might find helpful is to try and use json to respond to any ajax requests.
Code:
//application/config/constants.php
//Global define for AJAX Requests
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

//In your controller
if($this->form_validation->run() == FALSE)
{
  if(IS_AJAX){
    $data['response'] = 'failed';
    $data['message']  = validation_errors();
    echo json_encode($data);
  }else{
    $data['errors'] = validation_errors();
    $this->load->view('form', $data);
  }  
}else{
  //A successful routine here
  if(IS_AJAX){
    $data['response'] = 'true';
    $data['message']  = 'Success';
    echo json_encode($data);
  }else{
    $this->load->view('form_success', $data);
  }  
}

Now you will have a working form with the same code base that works with(out) js. Create some if statements handling the json response back.
#3

[eluser]landitus[/eluser]
Hi!, I'm looking into this Ajax form submit but cannot find a complete tutorial which uses CI validation and enhances the CI form submit process. There are bits and pieces in the forum but cannot figure it out.

a. I don't understand if it's possible to return validation errors for each field separately with Ajax and JSON. I'm using
Code:
<?php echo form_error('name'); ?>
under every field so the errors show in place. Can this be enhanced with AJAX.

b. Do you know any post or tutorial where I can see the full MVC and the jQuery code of an ajax enhanced contact form with validation errors?

Thanks!
#4

[eluser]Liu Guoqing[/eluser]
Hello!
#5

[eluser]pickupman[/eluser]
a. Yes, that's the advantage of using json to respond. You can return arrays. You will just need to loop through the json array to append a validation error to a field.

b. Don't get yourself to confused with MVC/CI and jQuery. It would work the same way in just php. It just MVC/CI provides a structure to your code.




Theme © iAndrew 2016 - Forum software by © MyBB