How to upload file and insert data with php jquery ajax

隐身守侯 提交于 2019-12-22 09:47:02

问题


I cannot send via ajax to php file upload and data with ajax. This my code just send file upload. data not send to my php code. I create form and the function send on click using ajax to post on php. I'm using codeigniter

This my form:

<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>

This javascript to send post on php using ajax:

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

I'm already try using $_POST['message']; and $this->input->post("message"); its not work both This php to proces code:

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

In database i'm just send name file upload.user, message, and iduser its not send.


回答1:


i think your problem may be in ajax code since you are using formData object . try append the message variable with it

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



回答2:


try to make ajax code like this.

  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) {

    }
  });

and your controller make like this it's working code for me

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



回答3:


I think the point @kunal was making was that you should not add potentially sensitive data as hidden inputs ( anyone can change it ) but should reference the values held in those fields directly within your class before adding to the db. In addition using embedded variables opens your app to sql injection so use a prepared statement.

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

I played around with your original javascript/jQuery code but could not get the function to work ( I don't use jQuery so I was guessing ) but using regular, vanilla javascript you can do it like this ~ the portion of php code at the top is not really relevant as you would be sending the ajax request to 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>


来源:https://stackoverflow.com/questions/47845081/how-to-upload-file-and-insert-data-with-php-jquery-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!