I'm going to take some liberties answering this question because I don't think I understand it.
First off, I don't know much about $.post()
, so I am going to answer you're question as if you we're you using $.ajax()
becuase that's what I know and I am pretty sure they are similar.
We then want Codeigniter to perform
validation but were not sure how to
return to a page to display the
validation errors?
You don't return to a page to display the errors, you echo them out so that jQuery can receive the output (like a CI view file) and you can then handle the result however you want.
Using $.ajax()
, here's what I would do..
The CI controller:
if( ! $this->form_validation->run($my_form_rules))
{
// Set the status header so $.ajax() recognizes it as an error
$this->output->set_status_header(400);
// The error string will be available to the $.ajax() error
// function in the javascript below as data.responseText
echo validation_errors();
exit();
}
else
{
// Do something with the post data
$result = $this->do_something();
// Set the status header so $.ajax(0 recognizes a success
// and set the header to declare a json response
$this->output->set_status_header(200);
$this->output->set_header('Content-type: application/json');
// Send the response data as json which will be availible as
// var.whatever to the $.ajax() success function
echo json_encode($result);
exit();
}
The ajax:
$.ajax({
data: myPostDataObj,
dataType: "json",
type: "POST",
success: function(data) {
alert(data.message);
},
error: function(data) {
alert(data.responseText);
}
});
You can read more about $.ajax()
in jQuery here, but basically, you're sending the post data to whatever controller you have setup, it takes that data, runs it through the validation process, and if it fails, it echoes out some standard text that ajax will send to your error function as var.responseText.
If it passes validation, you would do something with the post data, then return whatever results you want as a json object that can easily be used in you're javascript function.
I think that's probably a better solution, and I hope that helps explain a little bit of what's going. I hope.