Welcome Guest, Not a member yet? Register   Sign In
Ajax response issue when validating form
#1

[eluser]Unknown[/eluser]
hello people Smile,

I'm facing a problem with CodeIgniter form validation. I am passing form data to a controller using AJAX. but seems its never execute the form_validation function or validation_errors() function. But i am getting form data correctly. when I echo $this->input->get('any_form_field'), it output that field value.

this is the controller action:

Code:
public function add()
{    
$this->load->library('form_validation');

    $respond = array();
    if($this->form_validation->run('add_customer') !== FALSE)
    {
   $respond['result'] = 'true';
   $respond['message'] = 'Customer added successfully';
   echo json_encode($respond);
    }
    else
    {
   $respond['result'] = 'false';
   $respond['message'] = validation_errors();
   echo json_encode($respond);
    }
}

This is my scripts in the view file
Code:
$(function () {

  $('.test').click(function () {

   var form_data = {
    Name: $('.a').val(),
    Contact: $('.b').val(),
    Address: $('.c').val()
   };

   $.ajax({
    url: "<?=site_url('customer/add')?>",
    type: 'GET',
    data: form_data,
    dataType: 'json',
    success: function (data) {
     alert(data.result);
     alert(data.message);
    },
    error: function (data, m) {
     alert('Oops! Something happened.');
     alert(m);
    }
   });
  });
});

here is my validation rules.
Code:
$config = array(
'add_customer' => array(
  array(
   'field' => 'Name',
   'label' => 'Name',
   'rules' => 'trim|required|min_length[2]|max_length[25]|is_unique[tbl_customer.Name]|xss_clean'
  ),
  array(
   'field' => 'Contact',
   'label' => 'Contact',
   'rules' => 'trim|required|max_length[20]|xss_clean'
  ),
  array(
   'field' => 'Address',
   'label' => 'Address',
   'rules' => 'trim|required|max_length[300]|xss_clean'
  )
)
);

in the view file where the scripts are present, I am showing two alert. first shows the correct output (as the validation function never execute it always show false), but the second alert always shows empty.:ohh:

WHY it shows an empty alert message. it should show the validation_errors() message or the success message.

one more thing, i am using CI template library: http://williamsconcepts.com/ci/codeignit.../template/

anyone please help. I am really depressed about this one.

Thanks.
#2

[eluser]Unknown[/eluser]
Finally I found the problem. CI form validation doesn't work with GET. So, I copied the GET array into the POST array and it works fine :cheese:

Thanks
#3

[eluser]Unknown[/eluser]
I think this is related to CSRF being turned on. Check your config.php file and see.




Theme © iAndrew 2016 - Forum software by © MyBB