Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  23] [ 2]  / answers: 1 / hits: 155685  / 8 Years ago, sat, october 15, 2016, 12:00:00

I wrote this to upload an image to my local Apache webserver using input element in HTML. The file is logged as not empty, but why is the form_data completely empty?



$('#upload-image').change(function(e){
var file = e.target.files[0];
var imageType = /image.*/;
if (!file.type.match(imageType))
return;
console.log(file);
var form_data = new FormData();
form_data.append('file', file);
console.log(form_data);
$.ajax({
url: 'http://localhost/upload.php',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});

});


This is my upload.php on local webserver



<?php
header('Access-Control-Allow-Origin: *');
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
$target_path = $_SERVER['DOCUMENT_ROOT'] . /uploads/ . $_FILES['file']['name'];
echo $target_path;
}
?>


The console.log(response) logs all the code lines of PHP file, instead of the returned result of echo


More From » jquery

 Answers
13

When logging a formData object with just console.log(formData) it always returns empty, as you can't log formData.



If you just have to log it before sending it, you can use entries() to get the entries in the formData object



$('#upload-image').change(function(e) {
var file = e.target.files[0];
var imageType = /image.*/;

if (!file.type.match(imageType)) return;

var form_data = new FormData();
form_data.append('file', file);

for (var key of form_data.entries()) {
console.log(key[0] + ', ' + key[1]);
}

$.ajax({
url: 'http://localhost/upload.php',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});

});

[#60383] Thursday, October 13, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
denzelc

Total Points: 637
Total Questions: 89
Total Answers: 88

Location: Liechtenstein
Member since Wed, Dec 8, 2021
2 Years ago
;