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) {

                    }
                });

            });
3
  • 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? Commented Nov 15, 2017 at 13:10
  • 1
    Possible duplicate of How to inspect FormData? Commented Nov 15, 2017 at 13:12
  • Do formData.forEach(function(k,v){ console.log(k,v) }) Commented Nov 15, 2017 at 13:24

2 Answers 2

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]); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

regardless its still the same, i will edit my question to ease out with val()
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); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.