javascript - Codeigniter ajax form validation error -
i have researched code make validation 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 $key => $value) { # code... $data['messages']['key'] = form_error($key); } } echo json_encode($data); }
and 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 if else statement was:
if (response.success == true){ alert('success'); }else{ alert('failed'); });
but when put 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 validation fails.
you hard coding string 'key'
in php loop want variable $key
change
$data['messages']['key']
to
$data['messages'][$key]
Comments
Post a Comment