无法使用php-(codeigniter)将数据插入mysql

时间:2015-03-28 04:10:09

标签: php sql codeigniter

chat.php(控制器)

   function chat_insert(){
     $this->load->model('chat/chat_model');
     try{ $data = array(
     $this->chat_model->chat_inserting($data);
    }
     catch (Exception $exc){
    return $exc->getTraceAsString();
  }
  }

这里控制器类我调用模型类并在这里调用.js文本数据....

chat.php-(模型)

  function chat_inserting($data){
    try{
     $this->db->insert('comments',$data);
    }
    catch (Exception $exc){
 return $exc->getTraceAsString();
}

}

chat.js(JavaScript的)

function set_msg(){
   var type = $('#txtmsg').val();
   $.ajax({
         type: 'post',
        url: 'chat_insert',
        data: {'text':type},
        success: function (data) {
        },
        error:function(data){
            alert('error');
        }
       });
       }

chat1.php(视图)             查看插入数据的代码

         <tr>
         <td style="width: 310px">
                <input class="form-control input-sm"  id="txtmsg"       style="width: 350px" type="text" name="txtmsg" /></td>
            <td style="width: 85px">
                <input class="btn btn-warning"  id="Submit2" style="font-family: verdana, arial" type="button" value="Send" onclick="set_msg()"/></td>
            </tr>

1 个答案:

答案 0 :(得分:0)

在try块中创建$data期间,Controller中存在PHP错误。您必须关闭array()并将所需数据传递到其中。

function chat_insert() {

    $this->load->model('chat/chat_model');
    try{ 
        // Get Ajax Posted Data
        $text = $this->input->post('text');

        // Add msg to database
        $data = array('database_field_name'=>$text);
        $this->chat_model->chat_inserting($data);

        // Return Response
        $this->output->set_content_type("application/json")
                     ->set_output(json_encode(array('status'=>true)));
    }
    catch (Exception $exc){
        return $exc->getTraceAsString();
    }
}

在JavaScript中,在框架中传递控制器的完整URL是一种很好的做法。

function set_msg(){

   var type = $('#txtmsg').val();
   $.ajax({
      type: 'post',
      url: '//'+window.location.host+'/CONTROLLER_NAME/chat_insert',
      data: {'text':type}, 
      dataType: 'json', 
      success: function (response) {
          if( response.status === true ) {
             // Success msg
          }
          else {
            // Error msg
          }
      },
      error:function(data){
        alert('error');
      }
   });
}