2016-05-13 111 views
0

我想在我的網站上使用帶有Ajax的codeigniter的評論框。我想如果評論成功顯示新評論。否則顯示驗證錯誤。怎麼做?ajax Codeigniter表單驗證

這是我的控制器表單驗證

if ($this->form_validation->run() == TRUE) {  
      $this->load->model('comment_model'); 
      $this->load->model('user_model'); 
      if($this->comment_model->insert_comment()) 
      { 
       $data['user_comment']= $this->user_model->get_user_session($this->session->userdata('user_id')); 
       $data['new_comment']= $this->comment_model->get_one_comment(); 
       $this->load->view('user/insert_comment',$data); 
      } 
     } else { 
       echo validation_errors(); 
} 

這是我成功的AJAX功能。

success: function (data) { 
       if (data)// this is what is need. How to make a if condition 
       { 
        $('ol#update').prepend(data); 
        $('ol#update li:first').slideDown('slow'); 
       } 
       else 
       { 

        $('#myerror1').html(data); 
       } 

      } 

回答

1

從控制器返回答案作爲Json並在成功函數中解析它。

if ($this->form_validation->run() == TRUE) {  
    $this->load->model('comment_model'); 
    $this->load->model('user_model'); 
    if($this->comment_model->insert_comment()) { 
     $data['user_comment']=$this->user_model->get_user_session($this->session->userdata('user_id')); 
     $data['new_comment']= $this->comment_model->get_one_comment(); 
     // third argument means, return template as string instead of echo. 
     $data = $this->load->view('user/insert_comment',$data, TRUE); 
     $array = array(); 
     $array['success'] = true; 
     $array['data'] = $data; 

    } else { 
     $array = array(); 
     $array['success'] = false; 
     $array['data'] = validation_errors(); 
    } 
    echo json_encode($array); 
} 

而在成功的功能:

success: function (data) { 
    var jsonData = JSON.parse(data); 
    if (jsonData.success == true) { 
     $('ol#update').prepend(jsonData.data); 
     $('ol#update li:first').slideDown('slow'); 
    } else { 
     $('#myerror1').html(jsonData.data); 
    } 
}