PHP not receiving formData object from ajax - php

I'm testing out sending a formData object to PHP (I am following http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/), but am having some difficulty getting it off the ground. First, the formData object is created and populated with:
var formdata = new FormData();
formdata.append('my_key','my_value');
Then my ajax call with jQuery is:
$.ajax({
url: 'php_upload.php',
type: 'POST',
cache: false,
data: formdata,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
}
});
With the php_upload.php file containing:
<?php
echo $_FILES['my_key']['name'];
?>
But I get an undefined index: my_key error in the console.
Anyone have any idea what I might be doing wrong? Been scratching my head for ages.

You haven't added any files to the FormData, just a string which can be accessed by $_POST['my_key'].
To pass a file the second parameter of FormData.append has to be a FILE or a BLOB.

Related

PHP Ajax Post File and Text Same Time

I can post only image and get it with $_FILES['foto']['name']. I need post image and text same time.
var fotoFile = new FormData();
$('#foto').on('change', function (evt) {
var files = evt.target.files;
if (files.length > 0) {
fotoFile.append("foto", files[0]);
}
});
It is post code
` $.ajax({
url: 'postpages/personelsave.php',
dataType: 'text',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: {foto : fotoFile, tc_no : document.getElementById('tcNo').value},
success: function(php_script_response){
alert(php_script_response);
}
});`
and personelsave.php
$_FILES['foto']['type']
$_POST["tc_no"]
Error : undefined index foto.
What is wrong with it?
You can't use multiple dataTypes, if you use JSONP this will return a jsonp block which you could use to call a callback to handle the return data like this:
Basic example of using .ajax() with JSONP?
So through JSONP you can handle multiple dataTypes.
Just use below to submit all types of input data including file
var formData = new FormData($("#formID")[0]);
$.ajax({
type: "POST",
url: 'postpages/personelsave.php',
data: formData,
processData: false,
contentType: false,
});

Ajax file upload outside of form without plugins

I've been searching for a solution to upload files using Ajax when the input field is not inside a form tag. I have already tried this solution.
This is my HTML
<span id="user-image-up-btn">Last opp bilde</span>
<input id="user_image_upload" type="file" />
This is my code, and I get the return TypeError: undefined is not an object (evaluating '$("#user_image_upload").files') or when I use alternative number 2, I get Object, object.
This is my jQuery
// IMAGE UPLOAD
$("#user_image_upload").change(function() {
var fileform = new FormData();
fileform.append('pictureFile', $("#user_image_upload").files[0]);
$.ajax({
url: '/userimageupload',
type: 'POST',
processData: false,
contentType: false,
dataType : 'json',
data: fileform,
beforeSend: function(){
$("#user-image-up-btn").html('Laster opp...');
console.log(fileform);
},
success: function(data){
$("#user-image-up-btn").html('Last opp bilde');
console.log(fileform);
},
error: function(exception){
alert('error:'+exception);
console.log(fileform);
}
});
});
EDIT:
By using the answer from Adeneo I managed to upload the files. However, I still get error:[object Object], which causes the rest of the form to fail. How come?
A jQuery object has no files property, that would be the underlying DOM node
$("#user_image_upload").on('change', function() {
var fileform = new FormData();
fileform.append('pictureFile', this.files[0]);
$.ajax({
url: '/userimageupload',
type: 'POST',
processData: false,
contentType: false,
dataType : 'json',
data: fileform,
beforeSend: function(){
$("#user-image-up-btn").html('Laster opp...');
},
success: function(data){
$("#user-image-up-btn").html('Last opp bilde');
},
error: function(exception){
alert('error:'+exception);
}
});
});

Uploading multiple images with AJAX empty php response

I'm Trying to upload multiple images via post AJAX method, but if I upload more than 2 pictures, I get empty array response from PHP, but with 1 or 2, and sometimes 3 images, I get successful response! data is passed successfully to PHP all times, but response is like mystery !
my ajax
var id=data;
var file_data=$('#images').prop('files');
var formData = new FormData();
for(var x in file_data){
formData.append("image["+x+"]", file_data[x]);
}
formData.append("id", id);
$.ajax({
url: "ajax/ajax_add_car.php?veids=2",
enctype: "multipart/form-data",
method: "POST",
data: formData,
cache:false,
processData: false,
contentType: false,
success: function(data){
console.log(data);
},
})
mine PHP response:
foreach($_FILES as $lolz){
print_r($lolz);
}
print_r($_POST);

ajax send file and variable to php

I'm using an ajax call to upload a file, handled by PHP. The file should be placed in a specific directory based on a jquery variable. I can get the file to upload, but cannot pass the variable along with the file. PHP reports an undefined index error.
Ajax code:
var fd = new FormData();
fd.append( 'file', document.getElementById('select').files[0]);
$.ajax({
url: 'test.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function(e){
// some code here
}
});
I tried changing the data property to "fd+'&myVar='+myVar, however PHP cannot parse the data correctly and returns undefined index error for both the $_FILES['file'] variable as well as the $_POST['myVar'] variable.
How can I send both the file and a variable?
If you need another form field, call fd.append a second time:
fd.append('file', document.getElementById('select').files[0]);
fd.append('myVar',myVar);
You can append values other than files to a formdata object.
var fd = new FormData();
fd.append( 'file', document.getElementById('select').files[0]);
fd.append( 'myVar', myVar);
$.ajax({
url: 'test.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function(e){
// some code here
}
});
Refer to $.ajax jQuery API Documentation.
It is clearly stated that data should be an object with key-value pairs representing data accepted by server-side script. Whatever, not sure why jQuery seems to not accept your data. Maybe you should try this out manually.
Since your test.php accepts POST data as myVar your jQuery Ajax configuration should probably look like
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myVar: document.getElementById('select').files[0]
},
success: function(e){
// some code here
}
});

Can't use the array that php returns [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I am getting an array returned from PHP which I json_encode() in php first and I echo that array. I get the array with an AJAX request disabling "Async". I know I shouldn't use that but it was the only way I could find.
It returns me this:
{"id":"38","name":"111111111111111111111111111111111111111111111.jpg"}
And this is my AJAX request:
function uploadFile(file){
var formData = new FormData();
formData.append('formData', file);
$.ajax({
url: 'inc/ajax/uploadFile.php', //Server script to process data
type: 'POST',
data: formData,
contentType: false,
processData: false,
async: false,
//Ajax events
success: function(html){
strReturn = html;
}
});
return strReturn;
}
When I do this I get the whole array:
var img = uploadFile(file);
console.log(img);
But when I call "img.name" or img.id" it says undefined.
You're receiving back a JSON string representation of an object. Tell jQuery that you're expecting JSON, so that it parses it into an actual Javascript object for you:
data: formData,
dataType: 'json', // Add this line
You need set dataType to json and you should use a callback you are probably returning strReturn before it is populated.
function uploadFile(file,callback){
var formData = new FormData();
formData.append('formData', file);
$.ajax({
url: 'inc/ajax/uploadFile.php', //Server script to process data
type: 'POST',
data: formData,
contentType: false,
processData: false,
dataType: "json",
//Ajax events
success: function(html){
strReturn = html;
callback(strReturn);
}
});
}
uploadFile(file,function(img){
console.log(img.name);
});
Try this:
function uploadFile(file){
var formData = new FormData();
formData.append('formData', file);
$.ajax({
url: 'inc/ajax/uploadFile.php', //Server script to process data
type: 'POST',
data: formData,
contentType: false,
dataType: "json",
processData: false,
//Ajax events
success: function(html){
strReturn = html;
return strReturn;
}
});
}
It says undefined because the strReturn is not defined at the moment you return it. The ajax's success method is called with a delay of some milliseconds so you have to return your variable after the ajax is finished.

Categories