2

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

1 Answer 1

1

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")

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks @jmadsen but as I told I tested serialize and it still give me error. That I think because serialze() make the form a query string but nothing that can be understandable by $_POST. for example if I have 2 form element it becomes name1=value1&name2=value2 and will be put in $_POST['form_data']. So when codeigniter search for $_POST["name1"], the result will be false.
why is it going in form_data? it should just be going into POST vars as normal in your controller, do a var_dump($_POST) and see what's going on
form_data = $("myform").serialize(). As it's stated in jquery website serialize "Encode a set of form elements as a string for submission.". It means that after you call this function and assign it to some variable in data property of Ajax, it's just include a query string. You can see the example here [api.jquery.com/serialize/]. using var_dump also shows something like string(n) name1=value1&name2=value2&...
Don't assign it to a variable, just pass it as your data: part of the ajax call; that's what's causing your problem. You aren't passing serialize(), you're passing a string, and you don't want that
read the answer I already gave you, and look around on the web a bit, please
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.