kev_m kev_m - 5 months ago 161
Ajax Question

Codeigniter ajax form validation error

I have researched this code that will make my validation with ajax.

My controller is:

public function create(){


$data = array('success' => false, 'messages' => array());

$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');

if($this->form_validation->run($this)){

$data['success'] = true;
}else{
foreach ($_POST as $key => $value) {
# code...
$data['messages']['key'] = form_error($key);
}
}

echo json_encode($data);
}


And my javascript is:

<script>
$('#form-user').submit(function(e){
e.preventDefault();

var me = $(this);

// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response){
if (response.success == true){
alert('success');
}else{
$.each(response.messages, function(key, value) {
var element = $('#' + key);

element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();

element.after(value)

});
}
}

});


});


</script>


At first my if else statement was:

if (response.success == true){
alert('success');
}else{
alert('failed');

});


But when i put the codes:

$.each(response.messages, function(key, value) {
var element = $('#' + key);

element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();

element.after(value)


The button doesn't work anymore if the validation fails.

Answer

You are hard coding the string 'key' in the php loop where you actually want the variable $key

Change

$data['messages']['key']

To

$data['messages'][$key]