4

following is my code when i do console.log(formData); its empty. Cannot see a reason for it to fail down.

$("#add_meal_item").on('click', '#save_meal_item', function () {
                var meal_name = $("#add_meal_item_form").find('#meal_name').val();
                var meal_type = $("#add_meal_item_form").find('#meal_type').val();
                var logoImg = $("#add_meal_item_form").find('#meal_image').get(0).files[0];
                var formData = new FormData();
                formData.append('logo', logoImg);
                formData.append('meal_type', meal_type);
                formData.append('meal_name', meal_name);
                console.log(formData);
                var ajax_url = baseurl + '/save_meal_item';
                $.ajax({
                    url: ajax_url,
                    type: 'POST',
                    data: formData,
                    success: function (response) {

                    }
                });

            });
noobie-php
  • 6,817
  • 15
  • 54
  • 101
  • A `FormData` instance is not like a normal object (if it were you could just use one), logging it to the console does not display it's contents. Are you not seeing the data server-side? – Jared Smith Nov 15 '17 at 13:10
  • 1
    Possible duplicate of [How to inspect FormData?](https://stackoverflow.com/questions/17066875/how-to-inspect-formdata) – Jared Smith Nov 15 '17 at 13:12
  • Do formData.forEach(function(k,v){ console.log(k,v) }) – Nitin Dhomse Nov 15 '17 at 13:24

2 Answers2

4

You need to get elements values first and then append them to formData, Like this:

var meal_name = $("#add_meal_item_form").find('#meal_name').val();
formData.append('meal_name ', meal_name );

And to show all formData keys and values you have to use FormData.entries method :

for(var pair of formData.entries()) {
     console.log(pair[0]+ ', '+ pair[1]); 
}
YouneL
  • 8,152
  • 2
  • 28
  • 50
2

FormData.append() doesn't create enumerable properties for formData, you need to use the iterator from FormData.entries to iterate the values.

Demo

var formData = new FormData();
formData.append('logo', "11");
formData.append('meal_type', "22");
formData.append('meal_name', "33");

console.log(Object.keys(formData)); //[]
console.log(JSON.stringify(formData)); //{}

//use iterator
var formEntries = formData.entries();
//console.log(formEntries.next().value); 
//console.log(formEntries.next().value); 
//console.log(formEntries.next().value); 

//or simply use Array.from
var formEntries = Array.from(formData.entries());
console.log("formEntries " , formEntries); 
gurvinder372
  • 66,980
  • 10
  • 72
  • 94