How to upload file and insert data with php jquery ajax

雨燕双飞 提交于 2019-12-06 03:44:02

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

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

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