0

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

            }
0

1 Answer 1

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);
   } 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.