Do form validation with jquery ajax in codeigniter

后端 未结 6 994
猫巷女王i
猫巷女王i 2020-12-03 22:34

How can i do form validation in codeigniter if i don\'t want to refresh the page? Basically i do this:

    $config = array(
            array(
                       


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 23:17

    Try this is my working (Codeigniter 3.0) basic example to achieve what you want do

    include filename.js in your view

    document.getElementById("yourForm").reset();
    
    $(document).ready( function() {
    var yourForm = $('#yourForm');
      yourForm.submit( function(event) {
          event.preventDefault();
        $.ajax( {
          type: 'POST',
          url: yourForm.attr( 'action' ),
          data: yourForm.serialize(),
          success: function(data) {
                if (data.code == '200') {
                $('#message').html(data.message);    
                document.getElementById("yourForm").reset();
                }
          },
          error: function(data) {
             var response = data.responseText;
             var obj = jQuery.parseJSON(response);
                if (obj.code == '500') {
                    var i;
                    for (i = 0; i < obj.field.length; i++) {
                      name = obj.field[i];
                      $('.label-'+name).addClass('label-error');
                  errors = JSON.stringify(obj.validation);
                  validate = jQuery.parseJSON(errors);
                  $('.helper-'+name).html(validate[name]);
                    }
                }
          }
        } );
      } );
    } );
    

    view HTML form example In this example in am using className you can use id as well change filename.js file accordingly

    // Important text after className "label-" & "helper-" must be input name

    controller PHP code

    public function function_name()
    {
        if(!empty($_POST)) {
    
            $this->load->library('form_validation');
            $this->form_validation->set_rules('firstName','First Name','required|max_length[16]');
    
    
            if($this->form_validation->run())     
            {
                $params = array(
                    'firstName' => $this->input->post('firstName'),
                    );
                // Model returning $data['newRecord'] with $params and insertId 
                $data['newRecord'] = $this->Record_model->newRecord($params);
    
                $reply = array();
                $reply['code'] = 200;
                $reply['record'] = array(
                            'insertId' => $data['newRecord']['insertId'],
                            'firstName' => $data['newRecord']['firstName']
                            );
                $reply['message'] = 'Hello, ' .$data['newRecord']['firstName']. ' - We have received your message. ' .$data['newRecord']['insertId']. ' is your reference ID, for this communication.';            
                header('Content-Type: application/json; charset=UTF-8');
                print json_encode($reply);
            }
            else {
               $validation = $this->form_validation->error_array();
               $field = array();
                        foreach($validation as $key => $value) {
                            array_push($field,$key);
                        }
                $reply = array(
                    'code' => 500,
                    'field' => $field,
                    'validation' => $validation,
                    'message' => 'Submission failed due to validation error.'
                    );
                header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Problem', true, 500);
                header('Content-Type: application/json; charset=UTF-8');
                print json_encode($reply);
            }
        }
        else {
                $reply = array();
                $reply['code'] = 403;
                $reply['message'] = 'No Direct Access Allowed.';
                header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden', true, 403);
                header('Content-Type: application/json; charset=UTF-8');
                print json_encode($reply);
        }
    }
    

提交回复
热议问题