ajax 在codeigniter中使用jquery ajax进行表单验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37185883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 10:30:29  来源:igfitidea点击:

Do form validation with jquery ajax in codeigniter

ajaxformscodeignitervalidation

提问by meph

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

如果我不想刷新页面,如何在 codeigniter 中进行表单验证?基本上我这样做:

    $config = array(
            array(
                    'field' => 'c_name',
                    'label' => 'Name',
                    'rules' => 'trim|required'
            ),
            array(
                    'field' => 'c_job',
                    'label' => 'Job',
                    'rules' => 'trim|required',
                    )
    );
    $this->form_validation->set_rules($config);
    if($this->form_validation->run() == true)
            {
                $this->load->model('model');
                //.....
            }
    else{
            $this->load->view('view');
        }

But if i send data with ajax and the page doesn't refresh, How can i do form validation?

但是如果我用ajax发送数据并且页面没有刷新,我该如何进行表单验证?

Edit:

编辑:

Thanks @ Amra Kojon. That's good and works but the new problem is this:

谢谢@Amra Kojon。这很好并且有效,但新问题是:

if ($this->form_validation->run() == FALSE) {
                echo validation_errors();
                } 
                else {
                        //echo 'hi';


                        $value = $this->input->post('value');

                        $values = array(
                                'c_name' => $value['c_name'],
                                'c_job'=> $value['c_job'],
                                'c_address'=> $value['c_address'],
                                'c_phone'=> $value['c_phone'],
                                'c_mail'=> $value['c_mail'],
                                'c_state'=> $value['c_state'],
                                'c_intrest'=> $value['c_intrest'],
                                'c_added_info'=> $value['c_added_info']
                        );


                        $add = $this->customers_model->add_customer($values);
                        echo $add;
                }  

If i just say echo "something" in the else part, It works and if the validation were OK, It echo hi but if i write theme in database (Which the value array has data and in not ajax way, it insert date), It doesn't work and the else part isn't working!!!

如果我只是在 else 部分说 echo "something",它可以工作,如果验证没问题,它会回显你好,但如果我在数据库中写主题(值数组有数据而不是 ajax 方式,它插入日期),它不起作用,其他部分不起作用!!!

回答by TTareq

If you gave your JS- jquery Ajax code it would more efficient to understand your problem.. Don't worry! Try my following instruction...

如果你提供你的 JS-jquery Ajax 代码,它会更有效地理解你的问题..别担心!试试我的以下说明...

1) Get get form value and pass to form as

1) 获取表单值并传递给表单

<script type="text/javascript"> 
  $(document).ready(function(){
    var dataString = $("#FormId").serialize();
    var url="ControllerName/MethodName"
        $.ajax({
        type:"POST",
        url:"<?php echo base_url() ?>"+url,
        data:dataString,
        success:function (data) {
            alert(data);
        }
        });     
  })
</script>

Controller :

控制器 :

  1. Load library form_validation in construct as ...

    $this->load->library('form_validation');

    $this->load->helper('form');

  2. Now write your controller as ...

    function MethodName {
    $this->form_validation->set_error_delimiters('', '');
    $this->form_validation->set_rules('fname','First Name', 'required');
    $this->form_validation->set_rules('lname','Last Name', 'required');
    $this->form_validation->set_rules('email','Email Address','required|valid_email|is_unique[sec_users.email]');
    if ($this->form_validation->run() == FALSE) {
        echo validation_errors();
    } 
    else {
      // To who are you wanting with input value such to insert as 
      $data['frist_name']=$this->input->post('fname');
      $data['last_name']=$this->input->post('lname');
      $data['user_name']=$this->input->post('email');
      // Then pass $data  to Modal to insert bla bla!!
    }
    

    }

  1. 在构造中加载库 form_validation 为 ...

    $this->load->library('form_validation');

    $this->load->helper('form');

  2. 现在将您的控制器写为...

    function MethodName {
    $this->form_validation->set_error_delimiters('', '');
    $this->form_validation->set_rules('fname','First Name', 'required');
    $this->form_validation->set_rules('lname','Last Name', 'required');
    $this->form_validation->set_rules('email','Email Address','required|valid_email|is_unique[sec_users.email]');
    if ($this->form_validation->run() == FALSE) {
        echo validation_errors();
    } 
    else {
      // To who are you wanting with input value such to insert as 
      $data['frist_name']=$this->input->post('fname');
      $data['last_name']=$this->input->post('lname');
      $data['user_name']=$this->input->post('email');
      // Then pass $data  to Modal to insert bla bla!!
    }
    

    }

Hope will work as it is working in my application.

希望会在我的应用程序中发挥作用。

Please accept if it is the best answer.

如果是最佳答案,请采纳。

Thank you!

谢谢!

回答by Mr. ED

I know your question is a year old but you can use this for the latest bootstrap with codeigniter

我知道您的问题已经有一年了,但您可以将其用于 codeigniter 的最新引导程序

<?php

class Yourcontroller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
    }

    public function index() {
        $this->load->view('template/register');
    }

    public function validate() {

        $json = array();

        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[5]');
        $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required|matches[password]');
        $this->form_validation->set_rules('code', 'Login Code', 'required|numeric|min_length[4]||max_length[8]');

        $this->form_validation->set_message('required', 'You missed the input {field}!');

        if (!$this->form_validation->run()) {
            $json = array(
                'username' => form_error('username', '<p class="mt-3 text-danger">', '</p>'),
                'email' => form_error('email', '<p class="mt-3 text-danger">', '</p>'),
                'password' => form_error('password', '<p class="mt-3 text-danger">', '</p>'),
                'confirm_password' => form_error('confirm_password', '<p class="mt-3 text-danger">', '</p>'),
                'code' => form_error('code', '<p class="mt-3 text-danger">', '</p>')
            );
        }

        $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($json));

    }
}

Ajax Script

Ajax 脚本

<script type="text/javascript">
$( document ).ready(function() {
    $('#error').html(" ");

    $('#form-submit-button').on('click', function (e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "<?php echo site_url('yourcontroller/validate');?>", 
            data: $("#form").serialize(),
            dataType: "json",  
            success: function(data){
                $.each(data, function(key, value) {
                    $('#input-' + key).addClass('is-invalid');

                    $('#input-' + key).parents('.form-group').find('#error').html(value);
                });
            }
        });
    });

    $('#form input').on('keyup', function () { 
        $(this).removeClass('is-invalid').addClass('is-valid');
        $(this).parents('.form-group').find('#error').html(" ");
    });
});
</script>

Full View Code

完整查看代码

<div class="container">
    <div class="row">
        <div class="col-sm-6 ml-auto mr-auto m-auto">
            <div class="card mt-5">
                <h5 class="card-header"></h5>
                <div class="card-body">
                    <?php echo form_open('agent/register', array('id' => 'form', 'role' => 'form'));?>
                    <div class="row">
                    <div class="col-sm-12">
                    <div class="form-group">
                        <?php echo form_input('username', '', array('class' => 'form-control', 'placeholder' => 'Enter Agent Username', 'id' => 'input-username'));?>
                        <div id="error"></div>
                    </div>

                    <hr/>
                    </div>
                    </div>

                    <div class="row">
                    <div class="col-sm-12">
                    <div class="form-group">
                        <?php echo form_input('email', '', array('class' => 'form-control', 'placeholder' => 'Enter Agent Email', 'id' => 'input-email'));?>
                        <div id="error"></div>
                    </div>
                    <hr/>
                    </div>
                    </div>

                    <div class="row">
                    <div class="col-sm-6">
                    <div class="form-group">
                        <?php echo form_password('password', '', array('class' => 'form-control', 'placeholder' => 'Enter Password', 'id' => 'input-password'));?>
                        <div id="error"></div>
                    </div>
                    <hr/>
                    </div>


                    <div class="col-sm-6">
                    <div class="form-group">
                        <?php echo form_password('confirm_password', '', array('class' => 'form-control', 'placeholder' => 'Enter Confirm Password', 'id' => 'input-confirm_password'));?>
                        <div id="error"></div>
                    </div>
                    <hr/>
                    </div>
                    </div>

                    <hr/>

                    <div class="row">
                    <div class="col-sm-12">
                    <div class="form-group">
                        <button type="button" class="btn btn-block btn-dark" id="form-submit-button">Register Agent</button>
                    </div>
                    </div>
                    </div>

                    <?php echo form_close();?>

                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
$( document ).ready(function() {
    $('#error').html(" ");

    $('#form-submit-button').on('click', function (e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "<?php echo site_url('yourcontroller/validate');?>", 
            data: $("#form").serialize(),
            dataType: "json",  
            success: function(data){
                $.each(data, function(key, value) {
                    $('#input-' + key).addClass('is-invalid');

                    $('#input-' + key).parents('.form-group').find('#error').html(value);
                });
            }
        });
    });

    $('#agent-register-form input').on('keyup', function () { 
        $(this).removeClass('is-invalid').addClass('is-valid');
        $(this).parents('.form-group').find('#error').html(" ");
    });
});
</script>

回答by Arun

If you are aware about passing data with ajax, then the work flow is as follows.

如果你知道用ajax传递数据,那么工作流程如下。

1) Send form data through ajax to your controller.

2) Do form validation as of now.

3) If success then "echo" value 1

4) If failure, echo value 0

1)通过ajax发送表单数据到你的控制器。

2)现在做表单验证。

3)如果成功则“echo”值1

4) 如果失败,回显值 0

So that using the value in echo, you can determine whether the validation fails or not. I can give you an example if you need

这样就可以使用 echo 中的值来确定验证是否失败。如果你需要,我可以给你一个例子

Sample ajax code

示例 ajax 代码

$('#form').on('submit', function(e){
    e.preventDefault();
    var data = $(this).serialize();
    $.ajax({
        url: 'your url',
        type: 'POST',
        data: data,
        success: function(data){
            if(data == 1){
                $('#form')[0].reset();
                alret('success');
            }
            else if(data == 0){
                alret('failed');
            }
        },
        error: function(){
            alert('error');
        }
    });
});

回答by Mani

Create MY_Form_validation in libraries folder

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation {
private $json = array();
private $opts = array();

function get_json($extra_array = array(),$error_array=array())
    {
        if(count($extra_array)) {
            foreach($extra_array as $addition_key=>$addition_value) {
                $this->json[$addition_key] = $addition_value;
            }
        }
        $this->json['options'] = $this->opts;
        if(!empty($error_array)){
            foreach($error_array AS $key => $row)
                $error[] = array('field' => $key, 'error' => $row);
        }
        foreach($this->_error_array AS $key => $row)
            $error[] = array('field' => $key, 'error' => $row);


        if(isset($error)) {
            $this->json['status'] = 'error';
            $this->json['errorfields'] = $error;
        } else {
            $this->json['status'] = 'success';      
        }   
        return json_encode($this->json);
    }
}

Call this function in controller if validation failed:
echo $this->form_validation->get_json();

You get the response with form fieldname and errormessage

Example:
{"options":[],"status":"error","errorfields":[{"field":"email","error":"The Mobile Number\/Email\/Username field is required."},{"field":"password","error":"The Password field is required."}]}

回答by Mohsin Mujawar

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

试试这是我的工作(Codeigniter 3.0)基本示例来实现你想要做的

include filename.js in your view

在您的视图中包含 filename.js

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

查看 HTML 表单示例在此示例中使用 className 您可以使用 id 以及相应地更改 filename.js 文件

<form id="yourForm" action="base_url/controller/function_name" action="POST">
// Important text after className "label-" & "helper-" must be input name
<label class="label-firstName">Name</label>
<input type="text" name="firstName" />
<span class="helper-firstName"></span>
</form>
<div id="message"></div>

controller PHP code

控制器 PHP 代码

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);
    }
}

回答by Mhd Wael Jazmati

If using ajax,...you can't use form_validation library So you can validate on client side using jquery ...and on server side should use if statement to check submitted data

如果使用 ajax,...你不能使用 form_validation 库所以你可以使用 jquery 在客户端验证......并且在服务器端应该使用 if 语句来检查提交的数据