Ajax form validation in codeigniter
hellp guys,
I've been working on ajax recently, and I have a problem in using it with codeigniter form validation library. I used the example that tool generate in the function http://formtorch.geekhut.org/.
Now, ajax works perfectly and return data correctly when I use json_encode()
function with dummy data, but validation in the example uses validation
library instead of form_validation
library, which seems to be older version.
For that, validation didn't work with ajax in that example, specifically $this->form_validation->run()
function makes ajax return no result even if I echo dummy data using json_encode()
in the beginning of create_course()
.
so what's wrong with validation with ajax, and explain to me how data sent by ajax received by the controller.
so this is my code:
function create_course()
{
$this->form_validation->set_rules('course_code', 'course_code', 'trim|xss_clean|required');
$this->form_validation->set_rules('name', 'name', 'xss_clean|required');
// .. etc
if ($this->form_validation->run()) {
// validation ok
$data['course_code'] = $this->form_validation->set_value('course_code');
$data['name'] = $this->form_validation->set_value('name');
// ... etc
if ($this->models_facade->create_course($user_id,$data)) { // success
$data = array( 'profile_change' => $this->lang->line('profile_change'));
} else { // fail
$data = array( 'profile_change_error' => $this->lang->line('profile_change_error'));
}
}
else
{
$data = array(
'course_code' => $this->form_validation->course_code_error,
'name' => $this->form_validation->name_error
);
}
echo json_encode($data);
}
and this is the Jquery Ajax function
$(function(){
$("#submit").click(function(){
var course_code = $("#course_code").val();
var name = $("#name").val();
// etc
$.post("<?php echo base_url() ?>home/create_course", course_code:course_code, name:name},
function(data){
function(data){
aler开发者_高级运维t(data.data);
$("#course_code_error").html(data.course_code);
$("#name_error").html(data.name);
},'json');
});
return false;
});
Rather than printing out via "this->form_validation->xxxx_error" you can utilize Form Helper method "form_error()" to call the error messages.
So you can do something like..
$data = array(
'course_code' => form_error('course_code'),
'name' => form_error('name')
);
You might also consider setting the output content type header for JSON data.
$this->output->set_content_type('application/json');
echo json_encode($data);
What version of Codeigniter are you using? Did you remember to load the validation library in your construct?
$this->load->library('form_validation');
If you're making an ajax request you can use the validation_errors(). When the validation run it'll populate the array of error messages.
Here an exemple :
// Set your rules
$this->form_validation->set_rules('course_code', 'course_code', 'trim|xss_clean|required');
$this->form_validation->set_rules('name', 'name', 'xss_clean|required');
if ($this->form_validation->run()) {
//happy happy time
}
else {
//well now i'm sad...
//Important to turn that off if it's on
$this->output->enable_profiler(false);
$this->output->set_status_header('500');
$this->output->set_content_type('application/json');
echo json_encode(array(
'error_msg' => validation_errors(),
));
}
And then on your client-side you can use the response like that :
error:function(data) {
$("your-error-input-selector").html('').append(data.responseJSON.msg);
}
Hope i helped even if i'm 2 year late.
P.S Sorry for my broken english.
****//view-path [application/views/myviews/myview2.php]****
<script src="<?php echo base_url('/jquery-1.9.1.min.js');?>"></script>
<script>
$(document).ready(function() {
$("#frm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: $('#frm').attr('action'),
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log(data);
data = JSON.parse(data);
if(data.st == 0)
{
$( ".error-message" ).remove();
var data1 = JSON.parse(data.msg);
$('form :input').each(function(){
var elementName = $(this).attr('name');
var message = data1[elementName];
if(message){
var element = $('<div>' + message + '</div>')
.attr({
'class' : 'error-message'
})
.css ({
display: 'none'
});
$(this).before(element);
$(element).fadeIn();
}
});
}
if(data.st == 1)
{
$('#validation-error').html(data.msg);
$( ".error-message" ).remove();
}
},
error: function(){}
});
}));
});
</script>
<style>
.error-message{color:red;}
</style>
<?php echo form_open_multipart('ajaxcontroller/index', array('id'=>'frm')); ?>
<div id="validation-error"></div>
<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
<h5>Profile Pic</h5>
<input type="file" name="image[]" value="" multiple=""/>
<div><input type="submit" value="Submit" /></div>
</form>
**//controller--[application/controllers/ajaxcontroller.php]****
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajaxcontroller extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
if($_POST)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]');
$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
if (empty($_FILES['image']['name'][0])) {
$this->form_validation->set_rules('image[]', 'File', 'required');
}
if ($this->form_validation->run() == FALSE)
{
$errors = $this->form_validation->error_array(); //function in library : My_Form_validation
echo json_encode(array('st'=>0, 'msg' => json_encode($errors)));
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$email = $this->input->post('email');
if(is_array($_FILES)) {
foreach ($_FILES['image']['name'] as $name => $value){
if(is_uploaded_file($_FILES['image']['tmp_name'][$name])) {
$sourcePath = $_FILES['image']['tmp_name'][$name];
$targetPath = "images/".$_FILES['image']['name'][$name];
if(move_uploaded_file($sourcePath,$targetPath)) {
}
}
}
}
echo json_encode(array('st'=>1, 'msg' => 'Successfully Submiited'));
}
}
else
{
$this->load->view('myviews/myview2');
}
}
}
**//library file -- path will be [application/libraries/MY_Form_validation.php]**
<?php
/**
*
* Enter description here ...
* @return CI_Controller
*/
class MY_Form_validation extends CI_Form_validation
{
public function error_array()
{
return $this->_error_array;
}
}
精彩评论