2011-04-03 122 views
9

HELLP傢伙,Ajax表單驗證在笨

我一直對阿賈克斯最近,我在使用它與笨表單驗證庫有問題。我用這個工具在功能http://formtorch.geekhut.org/生成的例子。 現在,當我使用json_encode()功能與虛擬數據,但使用validation庫而不是form_validation庫似乎是舊版本時,ajax完美工作並正確返回數據。

爲此,驗證沒有與阿賈克斯在例如工作,特別是$this->form_validation->run()功能使得AJAX返回任何結果,即使我呼應的create_course()開始使用json_encode()虛擬數據。

有啥錯用AJAX驗證,並通過控制器接收ajax的數據如何發送給我解釋一下。

,所以這是我的代碼:

function create_course() 
{ 
     $this->form_validation->set_rules('course_code', 'course_code', 'trim|xss_clean|required'); 
     $this->form_validation->set_rules('name', 'name', 'xss_clean|required'); 
     // .. etc   
     if ($this->form_validation->run()) {    
      // validation ok 
      $data['course_code'] = $this->form_validation->set_value('course_code'); 
      $data['name'] = $this->form_validation->set_value('name'); 
      // ... etc 
      if ($this->models_facade->create_course($user_id,$data)) { // success 
        $data = array('profile_change' => $this->lang->line('profile_change')); 
      } else {     // fail 
        $data = array('profile_change_error' => $this->lang->line('profile_change_error')); 
      } 
     } 
     else 
     { 
      $data = array(
        'course_code' => $this->form_validation->course_code_error, 
        'name' => $this->form_validation->name_error 
      ); 
     }   
     echo json_encode($data); 
    } 

,這是Jquery的Ajax的功能

   $(function(){ 
    $("#submit").click(function(){ 
     var course_code = $("#course_code").val(); 
     var name = $("#name").val(); 
     // etc   
     $.post("<?php echo base_url() ?>home/create_course", course_code:course_code, name:name}, 
    function(data){ 
     function(data){ 
      alert(data.data); 
      $("#course_code_error").html(data.course_code); 
      $("#name_error").html(data.name); 
     },'json'); 
    }); 
    return false; 

});

您正在使用什麼版本笨的

回答

2

?你是否記得在你的構造中加載驗證庫?

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

「JSON」是它應該是「JSON」 – Khaled 2011-04-27 12:06:48

+0

它總是有一些小:) – tylerpenney 2011-05-10 19:24:35

7

,而不是通過「這個 - > form_validation-> xxxx_error」打印出可以利用表格Helper方法「form_error()」調用該錯誤消息。

所以,你可以做這樣的事情..

$data = array(
        'course_code' => form_error('course_code'), 
        'name' => form_error('name') 
      ); 
5

您也可以考慮設置JSON數據輸出的內容類型頭。

$this->output->set_content_type('application/json'); 
echo json_encode($data); 
+0

這是一個很好的提示問題。設置內容類型對於確定如何處理信息很重要。 – Manatax 2014-01-07 20:01:07

0

如果你正在做一個ajax請求,你可以使用validation_errors()。 當確認運行,它會填充錯誤消息的數組。

這裏的爲例:

// Set your rules 
$this->form_validation->set_rules('course_code', 'course_code', 'trim|xss_clean|required'); 
$this->form_validation->set_rules('name', 'name', 'xss_clean|required'); 

if ($this->form_validation->run()) { 
    //happy happy time 
} 
else { 
    //well now i'm sad... 

    //Important to turn that off if it's on 
    $this->output->enable_profiler(false); 

    $this->output->set_status_header('500'); 
    $this->output->set_content_type('application/json'); 

    echo json_encode(array(
     'error_msg' => validation_errors(), 
)); 
} 

,然後在您的客戶端可以使用這樣的迴應:

error:function(data) { 
    $("your-error-input-selector").html('').append(data.responseJSON.msg); 
} 

希望我幫助即使我2年晚。

P.S對不起,我蹩腳的英語。

0
****//view-path [application/views/myviews/myview2.php]**** 

    <script src="<?php echo base_url('/jquery-1.9.1.min.js');?>"></script> 
<script> 
$(document).ready(function() { 

    $("#frm").on('submit',(function(e) { 
     e.preventDefault(); 
     $.ajax({ 
      url: $('#frm').attr('action'), 
      type: "POST", 
      data: new FormData(this), 
      contentType: false, 
      cache: false, 
      processData:false, 
      success: function(data){ 
        console.log(data); 
        data = JSON.parse(data); 
        if(data.st == 0) 
        { 
         $(".error-message").remove(); 
         var data1 = JSON.parse(data.msg); 
         $('form :input').each(function(){        
             var elementName = $(this).attr('name');   
             var message = data1[elementName]; 
             if(message){ 
             var element = $('<div>' + message + '</div>') 
                 .attr({ 
                  'class' : 'error-message' 
                 }) 
                 .css ({ 
                  display: 'none' 
                 }); 
             $(this).before(element); 
             $(element).fadeIn(); 
             } 
         }); 
        } 

        if(data.st == 1) 
        { 
         $('#validation-error').html(data.msg); 
         $(".error-message").remove(); 
        } 
      }, 
      error: function(){}    
     }); 
    })); 

}); 
</script> 
<style> 
.error-message{color:red;} 
</style> 
<?php echo form_open_multipart('ajaxcontroller/index', array('id'=>'frm')); ?> 

<div id="validation-error"></div> 

<h5>Username</h5> 
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" /> 

<h5>Password</h5> 
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" /> 

<h5>Password Confirm</h5> 
<input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" /> 

<h5>Email Address</h5> 
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" /> 

<h5>Profile Pic</h5> 
<input type="file" name="image[]" value="" multiple=""/> 

<div><input type="submit" value="Submit" /></div> 

</form> 

**//controller--[application/controllers/ajaxcontroller.php]**** 

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

class Ajaxcontroller extends CI_Controller { 

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

    } 

    function index() 
    { 
     if($_POST) 
     {   
      $this->load->library('form_validation'); 
      $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]'); 
      $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]'); 
      $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); 
      $this->form_validation->set_rules('email', 'Email', 'required|valid_email'); 

      if (empty($_FILES['image']['name'][0])) { 
       $this->form_validation->set_rules('image[]', 'File', 'required'); 
      } 

      if ($this->form_validation->run() == FALSE) 
      { 
       $errors = $this->form_validation->error_array(); //function in library : My_Form_validation    
       echo json_encode(array('st'=>0, 'msg' => json_encode($errors))); 
      } 
      else 
      { 

       $username = $this->input->post('username'); 
       $password = $this->input->post('password'); 
       $email = $this->input->post('email'); 

       if(is_array($_FILES)) { 
        foreach ($_FILES['image']['name'] as $name => $value){ 
         if(is_uploaded_file($_FILES['image']['tmp_name'][$name])) { 
          $sourcePath = $_FILES['image']['tmp_name'][$name]; 
          $targetPath = "images/".$_FILES['image']['name'][$name]; 
          if(move_uploaded_file($sourcePath,$targetPath)) { 

          } 
         } 
        } 
       } 

       echo json_encode(array('st'=>1, 'msg' => 'Successfully Submiited')); 
      } 
     } 
     else 
     { 
      $this->load->view('myviews/myview2'); 
     }  
    } 

} 

**//library file -- path will be [application/libraries/MY_Form_validation.php]** 
<?php 
/** 
* 
* Enter description here ... 
* @return CI_Controller 
*/ 
class MY_Form_validation extends CI_Form_validation 
{ 
    public function error_array() 
    { 
     return $this->_error_array; 
    } 
} 
+0

使用jQuery的網址在網上或在您的客戶機存儲第一。 – 2015-08-01 11:42:58

+0

謝謝你的回答!請附上說明以及代碼以提供最佳答案。 – kittykittybangbang 2015-08-01 12:02:50