Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  152] [ 7]  / answers: 1 / hits: 60720  / 9 Years ago, sun, september 6, 2015, 12:00:00

lets jump right into the code :



var formData = new FormData();

formData.append('name', dogName);
formData.append('weight', dogWeight);
formData.append('activity', dogActivity);
formData.append('age', dogAge);
formData.append('file', document.getElementById(dogImg).files[0]);
console.log(formData);


Here I am appending some strings and one file object to the formData object in order to send all the information asynchronous to the server.



Right after that I have this jquery ajax request :



$.ajax({
type: POST,
url: /foodoo/index.php?method=insertNewDog,
data: JSON.stringify(formData),
processData: false, // tell jQuery not to process the data
contentType: multipart/form-data; charset=utf-8,
success: function(response){
console.log(response);
},
error: function(){
}
});


So here I am trying to POST the info to the server, on the server php file I have a simple print_r of the POST so I see what gets through and what not.



Unfortunately my response in the console.log(data) is empty.



Also if you check the HEADER in the Network tab you get the following empty output:



enter



Success function gets called (just for clarification)


More From » jquery

 Answers
12

When you're sending an ajax request via jQuery and you want to send FormData you don't need to use JSON.stringify on this FormData. Also when you're sending file the content type must be multipart/form-data including boundry - something like this multipart/form-data; boundary=----WebKitFormBoundary0BPm0koKA



So to send FormData including some file via jQuery ajax you need to:




  • Set data to the FormData without any modifications.

  • Set processData to false (Lets you prevent jQuery from automatically transforming the data into a query string).

  • Set the contentType to false (This is needed because otherwise jQuery will set it incorrectly).



Your request should look like this:



var formData = new FormData();

formData.append('name', dogName);
// ...
formData.append('file', document.getElementById(dogImg).files[0]);


$.ajax({
type: POST,
url: /foodoo/index.php?method=insertNewDog,
data: formData,
processData: false,
contentType: false,
success: function(response) {
console.log(response);
},
error: function(errResponse) {
console.log(errResponse);
}
});

[#65173] Thursday, September 3, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janayr

Total Points: 80
Total Questions: 80
Total Answers: 114

Location: Venezuela
Member since Sat, Aug 22, 2020
4 Years ago
janayr questions
Wed, Dec 29, 21, 00:00, 2 Years ago
Sun, Oct 31, 21, 00:00, 3 Years ago
Tue, Feb 4, 20, 00:00, 4 Years ago
;