How to upload file and insert data with php jquery ajax

Stfvns picture Stfvns · Dec 16, 2017 · Viewed 7.3k times · Source

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.

Answer

samehanwar picture samehanwar · Dec 16, 2017

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