php - 如何使用 php jquery ajax 上传文件和插入数据

标签 php jquery ajax codeigniter jquery-file-upload

我无法通过 ajax 发送到 php 文件上传和使用 ajax 的数据。 我的代码只是发送文件上传。数据没有发送到我的 PHP 代码。我使用ajax创建表单并点击发送函数以在php上发布。 我正在使用 codeigniter

这是我的表格:

<form action="<?php echo site_url('home/send_chat');?>" method="post" enctype="multipart/form-data">
  <input name="message" id="message" type="text" class="form-control input-sm" />
  <input type="file" id="file" name="file" />
  <br />
  <span class="input-group btn">
    <button type="submit" class="btn btn-info btn-sm" id="submit">Enkripsi</button>
  </span>
</form>

此 javascript 使用 ajax 在 php 上发送帖子:

$('#submit').on('click', function(){
  var message = $('#message').val();

  var fd = new FormData(this);
  fd.append('file',$('#file')[0].files[0]);

  $.ajax({
    method:"POST",
    url:"<?php echo site_url('home/send_chat');?>",    
    data: {fd,message:message},  
    cache: false,
    contentType: false,
    processData: false,   
    success: function(data){                 
      alert(data);
    },
    error: function(xhr, status, error) {
      alert(xhr.responseText);
    }  
  });
});

我已经尝试使用 $_POST['message'];$this->input->post("message"); 两者都不起作用 此 php 处理代码:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
  public function send_chat()
  {
    $name    = $_FILES['file']['name'];
    $error   = $_FILES['file']['error'];
    $size    = $_FILES['file']['size'];


    // $message = $_POST['message'];
    $message = $this->input->post("message");

    $user    = $this->session->userdata('username');
    $iduser  = $this->session->userdata('userID');



    $insert="insert into chat (user,message,id_user,fileupload) VALUES ('$user','$message','$userid','$name')";
    $this->db->query($insert);
  }
}

在数据库中,我只发送名称文件 upload.user、message 和 iduser,它不发送。

最佳答案

我认为您的问题可能出在 ajax 代码中 因为您正在使用 formData object 。尝试用它附加消息变量

$('#submit').on('click', function(){

  var fd = new FormData(this);
  fd.append('file',$('#file')[0].files[0]);
  fd.append('message ',$('#message').val());

  $.ajax({
    method:"POST",
    url:"<?php echo site_url('home/send_chat');?>",    
    data: fd,  
    cache: false,
    contentType: false,
    processData: false,   
    success: function(data){                 
      alert(data);
    },
    error: function(xhr, status, error) {
      alert(xhr.responseText);
    }  
  });
});

关于php - 如何使用 php jquery ajax 上传文件和插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47845081/

相关文章:

php - 即使数据库中有更多结果,PDO select 也只显示一个结果

php - 使用 AJAX 加载内容时更新 Facebook Like 元数据

javascript - jwt_authentication 请求 ajax - symfony

javascript - 使用 LESS 计算 DIV 高度

jquery - 在 jsFiddle 中使用 jQuery 主题 (CSS)

jquery - jQuery ajax错误处理程序函数存在,但仍引发异常

php - 无法使用PHP将所有数据插入MySQL

php - SQL select 语句中的语法错误

PHP/MySQL 如果行数大于 6400 则不返回任何结果

jquery - 用JS给iframe标签添加Id