17

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 image description here

Success function gets called (just for clarification)

Sahil
  • 428
  • 2
  • 7
  • 15
noa-dev
  • 3,561
  • 9
  • 34
  • 72
  • `JSON.stringify` only works with **plain** objects/arrays. `FormData` is not plain object. You have to pass [`FormData.getAll()`](https://developer.mozilla.org/en-US/docs/Web/API/FormData/getAll) instead of `FormData` – hindmost Sep 06 '15 at 08:35
  • data: JSON.stringify(formData.getAll()) ? This results in Uncaught TypeError: formData.getAll is not a function – noa-dev Sep 06 '15 at 08:39
  • Then don't use `JSON.stringify` at all. Pass `formData` as is. – hindmost Sep 06 '15 at 08:46
  • Okay, when I send it as it is - and then print_r the object in the php file and console.log it as a response i get a plain nothing ---- But the request Payload in the Header TAB in Network is now filled out with the send data – noa-dev Sep 06 '15 at 08:51

3 Answers3

24

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);
    }
});
Viktor Bahtev
  • 4,858
  • 2
  • 31
  • 40
  • 1
    I have enhanced my code to yours and - unfortunately the response is plain empty :( and by empty i don't mean "null" or so, its just an empty console.log – noa-dev Sep 06 '15 at 09:51
  • This is not working for me, look at my question here http://stackoverflow.com/questions/35954488/how-to-grab-formdata-being-passed-from-ajax-to-nodejs?noredirect=1#comment59565110_35954488 – Lion789 Mar 12 '16 at 07:33
  • formData.append('name', $("#idofinputfiled").val()); – EL TEGANI MOHAMED HAMAD GABIR Mar 10 '18 at 15:06
  • Thanks for this, I was looking all over for why I wasn't getting any data from my ajax request, but the trick was "Set data to the FormData without any modifications". I just had to append my extra fields to the formData object. – V1xIII Sep 07 '22 at 19:41
6

if you did exactly as pervious anwswer and still not working dont worry its working

maybe intelligence and quick wath are telling you its not working

enter image description here

but dont worry, look at network tap enter image description here

its working

hope this saves your time

Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92
2
//For those who use plain javascript

var form = document.getElementById('registration-form'); //id of form
var formdata = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST','form.php',true);
// xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
//if you have included the setRequestHeader remove that line as you need the 
// multipart/form-data as content type.
xhr.onload = function(){
 console.log(xhr.responseText);
}
xhr.send(formdata);
ajinkya
  • 31
  • 2
  • 5
    When answering, consider explaining the error/problem in the original question and how have you solved it. Don't forget that every question at StackOverflow is being viewed by a number of users and non-users to solve their similar problems. So for them to benefit from your answer, everyone would prefer to go through your explanation. – Mohammed Akhtar Zuberi Nov 26 '17 at 08:14
  • This answer save my day. !!! – Shurvir Mori Sep 27 '21 at 06:29