duanji6997 2017-07-22 15:26
浏览 29

too long

I have a form with server side validation using codeigniter built-in helper. I'm using ajax for sending data in my controller. It returns a json response which I am using in success function.

Here's the controller:

$this->form_validation->set_rules($this->validates()['create']);
       if($this->form_validation->run()){
           $response['status'] = true;
           $response['message'] = "Successfully added user";
           $response['page'] = base_url('/user');
           $this->user_model->user_add($this->form_input()['create']);
       }else{
           $errors = array();
           foreach ($this->input->post() as $key => $value) {
               $errors[$key] = form_error($key);
           }
           $response['errors'] = array_filter($errors);
           $response['status'] = false;
       }
    $this->jsonresponse($response);

Here's the ajax code:

 $.ajax({
        url:site_url('user/user_add'),
        data: $('#user_form').serialize(),
        type: 'post',
        dataType: 'json',
        beforeSend: function(){
            console.log('test');
        },
        success: function(response){
           if(response.status == true){
                alert(response.message);
           }else{
            $.each(response.errors,function(key,val){
                var names = ["firstname","middlename","lastname","username","job"];
                if(names.indexOf(key) > -1){

                     $('input[name="' + key + '"]').next().html(val);
                }else{
                    $('input[name="' + key + '"]').next().html('');
                }
            });

       }
        }
    });

Here's the view:

<div class="col-sm-10 col-md-10">
        <div class="row container-fluid well" style="background: white; border:3px groove orange;">
            <div class="col-md-12 ">
                <table id="patient_data" class="table display row-border table-condensed" width="100%">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>First Name</th>
                        <th>Middle Name</th>
                        <th>Last Name</th>
                        <th>Birthdate</th>
                        <th>Age</th>
                        <th>Gender</th>
                        <th>Bloodtype</th>
                        <th>Height</th>
                        <th>Weight</th>
                        <th>Address</th>
                        <th>Contact</th>
                        <th>Action</th>
                    </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</div>

<div class="modal fade" role="dialog" id="patient_modal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <span class="close" data-dismiss="modal">&times;</span>
                <h4 class="modal-title"></h4>
            </div>
            <div class="modal-body">
                <form id="patient_form" autocomplete="off">
                  <div class="row">
                  <input type="text" name="id" hidden>
                        <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>  
                        <div class="form-group">


                            <label for="firstname">Gender</label>
                            <div class="form-check">

                                <label for="gender" class="radio-inline" style="padding-right: 20px;">

                                    <input type="radio" id="female" name="gender" value="female">

                                    Female 
                                </label>
                                <label for="gender" class="radio-inline">
                                    <input type="radio" id="male" name="gender" value="male">
                                    Male
                                </label>
                                 <input type="radio" name="gender" value="" hidden checked>
                               <span class="text-danger"></span>
                            </div>  
                        </div>

                        <div class="form-group row">
                            <div class="col-md-6">
                                <label for="firstname">Birthdate</label>
                                <input type="date" id="birthdate" class="form-control" name="birthdate">
                                <span class="text-danger"></span>
                            </div>
                            <div class="col-md-6">
                                <label for="firstname">Age</label>
                                <input type="text" readonly class="form-control" name="age">

                            </div>
                        </div>
                        </div>
                        <div class="col-md-6">
                             <div class="form-group">
                            <label for="firstname">Height (cm)</label>
                            <input type="text" maxlength="3" class="form-control" name="height" class="extra">
                            <span class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label for="firstname">Weight (kg)</label>
                            <input type="text" maxlength="3" class="form-control" name="weight" class="extra">
                            <span class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label for="firstname">Blood Type</label>
                            <select name="bloodtype" class="form-control">
                                <option hidden selected></option>
                                <option value="A-">Blood Type A - Negative</option>
                                <option value="A+">Blood Type A - Positive</option>
                                <option value="B-">Blood Type B - Negative</option>
                                <option value="B+">Blood Type B - Positive</option>
                                <option value="AB-">Blood Type AB - Negative </option>
                                <option value="AB+">Blood Type AB - Positive</option>
                                <option value="O-">Blood Type O - Negative</option>
                                <option value="O+">Blood Type O - Positive </option>
                            </select>
                            <span class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label for="firstname">Address</label>
                            <input type="text" class="form-control" name="address">
                            <span class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label for="firstname">Contact Number</label>
                            <input type="text" maxlength="11" class="form-control" name="contact">
                            <span class="text-danger"></span>
                        </div>
                        </div>
                  </div>    
            <div class="modal-footer">
                <button class="btn btn-primary col-md-2 col-md-push-10 btn-sm submit" id="patient_action" type="button"></button>
                </form>
            </div>
        </div>
    </div>
</div>

I check if the response status from the controller is success or fail. If fail it will iterate the response errors then display it.

My problem is if a field is already valid it will not hide or remove. I use array with field names on it to checked if it contains the same as the response errors but it is not working.

Form validation is working and jsonresponse is a function in my MY_Controller which returns an json encoded data.

  • 写回答

1条回答 默认 最新

  • douye2020 2017-07-22 17:15
    关注

    Please refer this documentation for the set rule for validation https://www.codeigniter.com/userguide3/libraries/form_validation.html

    //$this->form_validation->set_rules($this->validates()['create']);
    

    if you set rule properly then change following in your code

    if($this->form_validation->run()){
       $response['status'] = true;
       $response['message'] = "Successfully added user";
       $response['page'] = base_url('/user');
       $this->user_model->user_add($this->form_input()['create']);
    }else{
       $response['errors'] = $this->form_validation->error_array();//generate error array with input post key
       $response['status'] = false;
    }
    //set page header in JSON format
    $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($response));
    

    change your success callback of Ajax

    success: function(response){
      //remove all errors
      $('#patient_form .form-group').find('span.text-danger').text('');
      if(response.status == true){
          alert(response.message);
      }else{
        var names = ["firstname","middlename","lastname","username","job"];
        //appent all errors 1-1
        $.each(response.errors,function(key,val){
          if(names.indexOf(key) > -1){
            $('#patient_form input[name="'+key+'"]').parent('.form-group').children('span.text-danger').text(val);
          }
        });
      }
    },
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看