It works fine for me.Set input textbox id and name as same...
Html :
<form id="myform" method="POST">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<button type="submit" id="submit_btn" class="btn btn-default">Submit</button>
</form>
Codeigniter validation :
public function validate()
{
$json = array();
$this->form_validation->set_rules('email','Email', 'required');
$this->form_validation->set_rules('pwd','Password', 'required');
if ($this->form_validation->run() == FALSE) {
$json = array(
'success' => 0,
'message' => 'Error occured',
'error' => $this->form_validation->error_array()
);
} else {
$data['email']=$this->input->post('email');
$data['pwd']=$this->input->post('pwd');
$json = array(
'success' => 1,
'message' => 'Data inserted successfully'
);
}
$this->output->set_content_type('application/json')->set_output(json_encode($json));
}
Ajax call :
<script type="text/javascript">
$(document).on('click', '#submit_btn', function() {
event.preventDefault();
var dataString = $("#myform").serialize();
var url="welcome/validate"
$.ajax({
type:"POST",
url:"<?php echo base_url() ?>"+url,
data:dataString,
success: function(json) {
try {
if (json['success'] == 1) {
alert(json['message']);
} else {
$('.error').hide();
var len = Object.keys(json['error']).length;
var error = json['error'];
if (len > 0) {
$.each(error, function( index, value ) {
if (value) {
$('#'+index).after('<p class="error">'+value+"</p>");
}
});
}
}
} catch (e) {
console.log('Exception while request..');
}
},
error: function() {
console.log('Error while request..');
}
});
})
</script>