Tech, Gaming and Food Enthusiast
Ajax callback validation routines with CodeIgniter
The CodeIgniter Form_Validation library is an extremely useful tool especially the ability to extend all core routines. Some validation requires real time PHP & MySQL processing, for example checking an email against those already registered with your site.
To use a PHP function to return values to the jQuery validate function, the only important theory to understand is that the function needs to echo, not return. Returning values will not send the output to the DOM and so the validation routines will not know what to do with it.
So here is an example of a function which uses a member model to check the email address against those already registered which will return boolean(true). The jQuery will post the information to this function.
function checkEmail() {
$this->load->model('members_model');
$email = $this->input->post('email');
if($this->members_model->checkDuplicate($email)) {
echo 'true';
} else {
echo 'false';
}
}
To call this function we need to use the jQuery validate remote option.
$('#myForm').validate({
rules: {
email: remote {
url: "path/to/checkEmail",
type: "post",
data: {
email: function() {
return $('#email').val();
}
}
}
}
});
This will provide real time PHP email validation which you can chose to fire on blur or on change or keyup. Your choice! Give it a go!
| Print article | This entry was posted by Matt on March 21, 2010 at 2:09 pm, and is filed under JavaScript, UX. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 2 years ago
Hello,
Thanks for the piece of code. It sounds exactly like what I need. I have tired it but got an error with Firebug:
missing } after property list
[Break on this error] email: remote {\n
The backets seem fine in my code though… Is there any particular Ajax library to include to make that code work? Sorry, but it’s the first time I use Ajax with the jQuery framework.
Thanks.
about 2 years ago
Yes, you need the jQuery validate library.
about 2 years ago
Nice Tut
about 2 years ago
Thanks
about 2 years ago
about 2 years ago
thanks