Nam Hao
Nam Hao

Reputation: 67

Codeigniter form validation with ajax

I want to have a comments box in my website using codeigniter with Ajax. I want if the comment success show new comment. Else show validation error. How to do it?

This is my controller form validation

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

This is my ajax success function.

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

            }

Upvotes: 0

Views: 79

Answers (1)

Return answer from controller as Json and parse it in success function.

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

And in success function:

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

Upvotes: 1

Related Questions