Sobhan Atar
Sobhan Atar

Reputation: 500

Using Codeigniter Form Validation with Jquery serialize

I want to use form validation methods of CI for validating my input data. As the form submitted via AJAX I'm using serializeArray() to post data to my controller so I don't have to post on by one data or wrinting some each() function. The problem is that form validation look for data in $_POST. Using serialize() didn't help neither. Is there any solution beside extending form validation library?

here my code: (controller)

$form_data = $this->input->post('form_data');

$this->load->library('form_validation');
$this->form_validation->set_rules('p_company_name', 'نام شرکت', 'required');
if ($this->form_validation->run() == FALSE)
{
  echo "fail";die(); // if i use serialize() or serializeArray()
}
else
{
  echo "success";die(); // if i use label:value for each form input
}

js code:

$.ajax({
    type: "POST",
    cache: false,
    url: url,
    data: {'form_data': form_data},
    dataType: "html",
    success: function(res, textStatus, xhr) 
    {
        //  do something
    },
    error: function(xhr, textStatus, thrownError)
    {
        //do something else
    },
    complete: function()
    {
        // do some final thing
    },
    async: true
});

Thanks in advance

Upvotes: 2

Views: 2407

Answers (1)

jmadsen
jmadsen

Reputation: 3675

post your data as:

data: form.serialize(),

and it will work as normal (form being a normal jquery reference to your page form, not just the word "form")

Upvotes: 1

Related Questions