Reputation: 155
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.)
Upvotes: 1
Views: 1000
Reputation: 127
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';
}
Upvotes: 0
Reputation: 609
data: {file: file}
try replacing your data line with this
and in php
$file = $_POST['file'];
Upvotes: 1