通过jQuery的Ajax和codeigniter得到验证错误 [英] get validation errors through jquery ajax and codeigniter

查看:153
本文介绍了通过jQuery的Ajax和codeigniter得到验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我只想问,为什么我的Ajax请求并获得(它应该得到的错误从控制器消息)的字符串。

下面是控制器的片段

 函数ajax_verify(){
    $这个 - > form_validation-> set_rules('用户名','','MAX_LENGTH [25] | MIN_LENGTH [4] |修剪|需要| xss_clean');
    $这个 - > form_validation-> set_rules('邮件','','VALID_EMAIL |需要|修剪| xss_clean');

    如果($这个 - > form_validation->运行()== FALSE){
             $错误= $这个 - > form_validation-> error_array();
             回声json_en code($这个 - > form_validation-> error_array());
    }其他{
            回声成功!;
       }

    }
 

我扩展了图书馆获得错误信息(这工作完全正常的PHP验证)

 类MY_Form_validation扩展CI_Form_validation {


功能__construct(){
    父:: __结构();
}

功能error_array(){
    如果(计数($这个 - > _error_array)=== 0){
        返回FALSE;
    }其他{
        返回$这个 - > _error_array;
    }
}

功能get_tae(){
    返回TAE!;
 }
}
 

和持续的视图和jQuery的AJAX code(回归,而不是错误的错误)。

 <!DOCTYPE HTML>
     < HTML>
     < HEAD>
          <元字符集=utf-8>
          &所述;脚本的src =htt​​p://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js>&所述; /脚本>
         <冠军>标题< /标题>
     <身体GT;

    < PHP //回声validation_errors('< D​​IV CLASS =错误>','< / DIV>');?>
    <?PHP的回声form_open(AJAX / ajax_verify',阵列('身份证'=>'my_form'));?>
    <?PHP的回声form_label(用户名); ?>
    <?PHP的回声form_input('用户名','',阵列('身份证'=>'用户名'));?>
    <?PHP的回声form_label(电子邮件地址); ?>
    <?PHP的回声form_input('邮件','',阵列('身份证'=>电子邮件)); ?>
    <?PHP的回声form_submit(提交,提交); ?>
    <?PHP的回声form_close();?>

    <脚本类型=文/ JavaScript的>
     $(函数(){
          $('#my_form)。递交(函数(五){
                $获得('ajax_verify',功能(数据){
                    $('#内容')追加(数据);
                },'JSON');
                即preventDefault();
            })


      });
           < / SCRIPT>
 

解决方案

试试这个。这将正常工作。

在控制器添加这两种方法

 公共职能CreateStudents(){

        $这个 - >负载>帮手(形式);

        $数据['标题'] =创建大学生页;
        $数据['成功'] =;
        $这个 - >负载>查看('模板/头,$数据);
        $这个 - >负载>查看('createstudents',$数据);
        $这个 - >负载>查看('模板/页脚,$数据);

    }

    公共职能CreateStudentsAjax(){

        $这个 - >负载>帮手(形式);
        $这个 - >负载>库('form_validation');
        $这 - > form_validation-> set_error_delimiters('','');

        $这个 - > form_validation-> set_rules('滚','卷号','需要');
        $这个 - > form_validation-> set_rules(名称,名称,需要');
        $这个 - > form_validation-> set_rules(手机,手机,要求);

        如果($这个 - > form_validation->运行()){

            $这个 - > welcome_model-> InsertStudents();
            回声json_en code(OKS);
        } 其他 {

            $数据=阵列(
                '滚'=> form_error('滚'),
                '名'=> form_error(名称),
                '电话'=> form_error(手机)
            );

            回声json_en code($的数据);
        }
    }
 

在视图中添加的格式的和的 DIV 的名为 mesage

 < D​​IV ID =消息>


        < / DIV>

        <?PHP的回声form_open(欢迎/ CreateStudentsAjax'); ?>

        <标签=滚>学生卷号和LT; /标签>
        <输入类型=文本ID =txtRoll值=NAME =滚/>

        <标签=名称>学生姓名和LT; /标签>
        <输入类型=文本ID =改为txtName值=NAME =名/>

        <标签=电话>电话号码和LT; /标签>
        <输入类型=文本ID =txtPhone值=NAME =电话/>

        <输入类型=提交名称=提交值=插入新学​​生/>

        < PHP的echo'< /形式GT;'; ?>
 

现在的脚本包含

 <脚本类型=文/ JavaScript的>

            $(文件)。就绪(函数(){

                $(形式)。递交(函数(){
                    //警报('OK');
                    $阿贾克斯({
                        网址:this.action,
                        类型:this.method,
                        数据:$(本).serialize()
                        成功:功能(数据){
                            变种物镜= $ .parseJSON(数据);

                            如果(OBJ ['滚']!= NULL)
                            {
                                $('#信息)文本()。
                                $('#信息)HTML(OBJ ['滚']);
                                $('#消息'),追加(OBJ ['名称']);
                                $('#消息'),追加(OBJ ['电话']);
                            }
                            其他
                            {
                                $('#信息)文本()。
                                $('#信息)HTML(OBJ);
                            }

                        },
                        埃罗:函数(){
                            警报(请重试);
                        }
                    });
                    返回false;
                });
            });

        < / SCRIPT>
 

Hi guys i just want to ask why my ajax request does get an string of FALSE (it should get the error messages from controller).

Here is the snippet of controller

    function ajax_verify(){
    $this->form_validation->set_rules('username', '', 'max_length[25]|min_length[4]|trim|required|xss_clean');
    $this->form_validation->set_rules('email', '', 'valid_email|required|trim|xss_clean');  

    if($this->form_validation->run()==FALSE){
             $errors = $this->form_validation->error_array();
             echo json_encode($this->form_validation->error_array());
    }else{
            echo "Success!";
       }

    }

I Extended the Library to get the error Messages (It works perfectly fine in php validation)

class MY_Form_validation extends CI_Form_validation{


function __construct(){
    parent::__construct();
}

function error_array(){
    if(count($this->_error_array)===0){
        return FALSE;
    }else{
        return $this->_error_array;
    }
}

function get_tae(){
    return "TAE!";
 }
}

and last the view and the jquery ajax code (Returning false instead of the errors).

     <!DOCTYPE HTML>
     <html>
     <head>
          <meta charset="utf-8">
          <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
         <title>Title</title>
     <body>

    <?php //echo validation_errors('<div class="error">', '</div>');?>
    <?php echo form_open('ajax/ajax_verify', array('id'=>'my_form'));?>
    <?php echo form_label('Username'); ?>
    <?php echo form_input('username', '', array('id' => 'username'));?>
    <?php echo form_label('Email Address'); ?>
    <?php echo form_input('email', '', array('id' => 'email')); ?>
    <?php echo form_submit('submit', 'Submit'); ?>
    <?php echo form_close();?>

    <script type="text/javascript">
     $(function(){
          $('#my_form').submit(function(e){
                $.get('ajax_verify', function(data){
                    $('#contents').append(data);
                }, 'json') ;                   
                e.preventDefault();
            })


      });
           </script>

解决方案

Try this. It will work fine.

In controller Add these two method

 public function CreateStudents() {

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

        $data['title'] = "Create Students Page";
        $data['success'] = "";
        $this->load->view('templates/header', $data);
        $this->load->view('createstudents', $data);
        $this->load->view('templates/footer', $data);

    }

    public function CreateStudentsAjax() {

        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('', '');

        $this->form_validation->set_rules('roll', 'Roll Number', 'required');
        $this->form_validation->set_rules('name', 'Name', 'required');
        $this->form_validation->set_rules('phone', 'Phone', 'required');

        if ($this->form_validation->run()) {

            $this->welcome_model->InsertStudents();
            echo json_encode("Oks");
        } else {

            $data = array(
                'roll' => form_error('roll'),
                'name' => form_error('name'),
                'phone' => form_error('phone')
            );

            echo json_encode($data);
        }
    }

In View Add the form and a DIV named "mesage"

<div id="message">


        </div> 

        <?php echo form_open('welcome/CreateStudentsAjax'); ?>

        <label for="roll">Student Roll Number</label>
        <input type="text" id="txtRoll" value="" name="roll"/>

        <label for="Name">Students Name</label>
        <input type="text" id="txtName" value="" name="name"/>

        <label for="Phone">Phone Number</label>
        <input type="text" id="txtPhone" value="" name="phone"/>

        <input type="submit" name="submit" value="Insert New Students"  />

        <?php echo '</form>'; ?>

Now the scripts contains

<script type="text/javascript">

            $(document).ready(function(){

                $('form').submit(function(){
                    //alert('ok');      
                    $.ajax({
                        url:this.action,
                        type:this.method,
                        data:$(this).serialize(),
                        success:function(data){
                            var obj = $.parseJSON(data);

                            if(obj['roll']!=null)
                            {                               
                                $('#message').text("");
                                $('#message').html(obj['roll']);
                                $('#message').append(obj['name']);
                                $('#message').append(obj['phone']);
                            }
                            else
                            {                               
                                $('#message').text("");
                                $('#message').html(obj); 
                            }

                        },
                        erro:function(){
                            alert("Please Try Again");
                        }                        
                    });
                    return false;
                });                        
            });

        </script>

这篇关于通过jQuery的Ajax和codeigniter得到验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆