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

时间:2017-12-16 11:19:09

标签: php jquery ajax codeigniter jquery-file-upload

我无法通过ajax发送到php文件上传和ajax数据。 This my code just send file upload。数据不发送到我的PHP代码。我创建表单和函数发送单击使用ajax发布在PHP上。 I'm using 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,而不是发送。

4 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

尝试制作像这样的ajax代码。

  var data = new FormData();
  jQuery.each(jQuery('#file')[0].files, function(i, file) {
    data.append('file', file);
  });
  $.ajax({
    type : "POST",
    url : "<?=base_url()?>home/send_chat",
    data : data,
    cache: false,
    contentType: false,
    processData: false,
    success: function(data) {

    }
  });

并且您的控制器就像这样,它是我的工作代码

class Home extends CI_Controller {

  function singleImageUpload($upload_name,$folder,$extension,$bnr,$filename)
  {
      if($folder == '')
      {
          $config['upload_path'] = 'images/agent';
      }
      else
      {
          $config['upload_path'] = 'upload/'.$folder."/";
      }
      $config['allowed_types'] = '*';
      if($bnr == 2)
      {
          $config['max_width'] = '3000';
          $config['max_height'] = '3000';
      }
      elseif ($bnr == 1)
      {}
      // $config['file_name'] = $user_name.date('YmdHis').".".$extension;
      $config['file_name'] = $filename;

      $this->upload->initialize($config);
      $this->load->library('upload', $config);
      if ( ! $this->upload->do_upload($upload_name))
      {
          $arrayRetutn['upload'] = 'False';
          $arrayRetutn['error'] = $this->upload->display_errors();
      }
      else
      {
          $arrayRetutn['upload'] = 'True';
          $arrayRetutn['data'] = $this->upload->data();
      }
       //echo '<pre>';print_r($arrayRetutn);echo '</pre>'; die;
      return $arrayRetutn;
  }

  public function send_chat()
  {
    $user    = $this->input->post("user");
    $message = $this->input->post("message");
    $iduser  = $this->input->post("iduser");

    if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != '')
    {
        $image_name = explode(".",$_FILES['file']['name']);
        $imgData = $this->singleImageUpload('file','your folder name',$image_name[1],'2',$_FILES['file']['name']);
        if($imgData['upload']=='True')
        {
            $name = $imgData['data']['file_name'];
        }
    }

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

答案 2 :(得分:0)

我认为@kunal的观点是你不应该将潜在敏感数据添加为隐藏输入(任何人都可以更改它),但是在添加到数据库之前应该直接在类中引用这些字段中保存的值。此外,使用嵌入式变量可以打开应用程序进行sql注入,因此请使用预准备语句。

<?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'];

        $user    = $this->session->userdata('username');
        $iduser  = $this->session->userdata('userID');
        $message = $this->input->post("message");


        $sql="insert into `chat` ( `user`, `message`, `id_user` ,`fileupload` ) values (?,?,?,?)";
        $stmt=$this->db->prepare( $sql );
        if( $stmt ){
            $stmt->bind_param('ssss',$user,$message,$userid,$name);
            $stmt->execute();
        }
      }
    }

我玩了你原来的javascript / jQuery代码,但无法使用该功能(我不会使用jQuery,所以我猜)但是使用常规,vanilla javascript你可以这样做〜部分顶部的PHP代码并不真正相关,因为您将ajax请求发送到home/send_chat

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();
        /* send some sort of response...    */
        echo json_encode( $_POST );

        exit();
    }
?>
<!doctype html>
<html>
    <head>
        <meta charset='utf-8' />
        <title>xhr upload - no jquery</title>
        <script>
            document.addEventListener('DOMContentLoaded',function(){

                var callback=function( data ){
                    alert( data )
                }

                document.getElementById('submit').onclick=function(e){
                    e.preventDefault();
                    var url='<?php echo site_url('home/send_chat');?>';

                    var _file=document.querySelector('input[type="file"]');
                    var _form=document.querySelector('form[id="usr-upload"]');

                    var xhr = new XMLHttpRequest();
                    var fd=new FormData( _form );
                        fd.append('file', _file.files[0]);

                    xhr.onreadystatechange=function(){
                        if( xhr.readyState==4 && xhr.status==200 )callback.call( this, xhr.response );
                    };
                    xhr.onerror=function(err){
                        alert(err);
                    };
                    xhr.open('POST',url,true);
                    xhr.send( fd );
                };
            },false );
        </script>
    </head>
    <body>
        <form id='usr-upload' method='post' enctype='multipart/form-data'>
          <input name='message' type='text' />
          <input type='file' name='usrfile' />
          <br />
          <span class='input-group btn'>
            <input type='button' value='Enkripsi' id='submit' />
          </span>
        </form>
    </body>
</html>

答案 3 :(得分:0)

使用ajax提交所有数据,无论是否有文件

<form method="post" action="" enctype="multipart/form-data" id="form"/>
   // your own input fields
</form>

$("#form").submit(function (event) {
 event.preventDefault();
 //tinyMCE.triggerSave();
$.ajax({
    url: "<?php echo base_url('your_own_controller/your_own_method'); ?>",
    type: "post",
    data: new FormData(this),
    processData: false,
    contentType: false,
    cache: false,
    async: false,

    beforeSend: function () {}, //if you like to do something before submit
    complete: function () {}, //if you like to do something before submit 

    success: function (response) {
     //check response and do some your own stuff
    };
});