1

I want to send a file from an input to a php script, using ajax. Here is what I've done so far:

HTML

  <div id="inserting">
     <button id="inserting_btn">Upload</button>
     <input type="file" id="inserting_file"/>
   </div>

JS

$('#inserting_btn').click(function(){
        var file = $('#inserting_file').val();
        $.ajax({
            method: 'POST',
            url: 'input_text/import.php',
            data: 'file='+file,
            success: function(data){
                alert(data);
            }
        });
    });

PHP file import.php

if ($_FILES['file']['tmp_name'] ){
       echo 'yes';
    }
    else {
        echo 'no';
    }

(Sorry for my english.)

GramThanos
  • 3,572
  • 1
  • 22
  • 34
Toprex
  • 155
  • 1
  • 9

2 Answers2

1
data: {file: file}

try replacing your data line with this

and in php

 $file = $_POST['file'];
Chris Hutchison
  • 601
  • 6
  • 20
0

Try to change this in your code :

$('#inserting_btn').click(function(){
    var file_rec = $('#inserting_file').prop("files")[0]; // get the file
    var form_data = new FormData();                  
    form_data.append('file', file_rec);
    $.ajax({
        method: 'POST',
        url: 'input_text/import.php',
        data: form_data,
        success: function(data){
            alert(data);
        }
    });
});

PHP file import.php

if ($_FILES['file']){
   echo 'yes';
}
else {
    echo 'no';
}
Fahem Idir
  • 127
  • 2