1

I'm writting a code using CodeIgniter

ajax

  var formData = {};
  var url      = $(form_id).attr("action");
  $(form_id).find("input[name]").each(function (index, node) {
    formData[node.name] = node.value;
  });
  $(form_id).find('select[name]').each(function (index, node) {
    formData[node.name] = node.value;
  });
  $(form_id).find('textarea[name]').each(function (index, node) {
    formData[node.name] = node.value;
  });
  $.ajax({
    type: "POST",
    data: {
      'formdata': formData
    },
    url: url,
    dataType: 'json',
    success: function(result) {
      if (result.data) {
        make_alert();
      } else {
        $('#error-msg').html(result.message);
      }
    },
    error: function(result) {
     // error code here
    }
  });

Which will sent a data formData to add function in controller

add function

$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
        array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('email', 'Email', 'required');

and this part here receive the formData values

  $post_data = $this->input->post('formdata');
  $data = array (
    'username' => $post_data['username'],
    'email'    => $post_data ['email'],
    'password' => $post_data ['password']
  );

and this part run the validation

if ($this->form_validation->run() == FALSE) {
  $result['message'] = validation_errors();
} else {
  $result['data'] = $this->ion_auth->register($data['identity'], $data['password'], $data['email'], $data['additional_data'], $data['group']);
}

which return json

echo json_encode($result);

before using ajax, the code run smoothly without problem, but when using ajax, the validator return a message saying fields should be required, meaning, it doesn't receive form data submitted.

this part,

  $data = array (
    'username' => $post_data['username'],
    'email'    => $post_data ['email'],
    'password' => $post_data ['password']
  );

when using var_dump() on $data show it received form data submitted using ajax.

My question is, how to validate this $data using form_validation?

1
  • Seems like the data is not passed inside if(result.data) Commented May 12, 2016 at 10:25

1 Answer 1

2

You cant validate using form_validation library You should validate manually usin if statement and you will set error message as you want

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

Comments

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.