Welcome Guest, Not a member yet? Register   Sign In
Showing form validation errors individually using AJAX
#1

I want to individually show form validation errors under each input fields. I got it to work but the problem is if the field is already valid the element which handles the form error is not hiding.

Here's my ajax code:

Code:
function patient_add(){
    $.ajax({
        url: site_url('patient/patient_add'),
        data: $('#patient_form').serialize(),
        type: 'post',
        dataType: 'json',
       success: function(response){
        if(response.status === true){
            user_success(' fa fa-check-o','green',response.message,false);
            setTimeout(function(){window.location.href = response.page;},3000);
        }else{
                $.each(response.errors,function(key,val){
                    $('input[name="' + key + '"]').next().html(val).addClass('has-error');
                    $('select[name="' + key + '"]').next().html(val).addClass('has-error');
                });
            }
        }
    });
}
Here's my view:

Code:
<div class="col-md-6">
                             <div class="form-group">
                            <label for="firstname">First Name</label>
                            <input type="text" class="form-control" name="firstname">
                            <span class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label for="firstname">Middle Name</label>
                            <input type="text" class="form-control" name="middlename">
                            <span class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label for="firstname">Last Name</label>
                            <input type="text" class="form-control" name="lastname">
                            <span class="text-danger"></span>
                        </div>

Here's the controller portion.
Code:
 $error = array();
            foreach($this->input->post() as $key => $val){
              $error[$key] = form_error($key);
            }
            $response['errors'] = array_filter($error);
            $response['status'] = false;
Reply


Messages In This Thread
Showing form validation errors individually using AJAX - by nullstrike - 07-23-2017, 04:07 AM



Theme © iAndrew 2016 - Forum software by © MyBB