Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formdata object shows empty even after calling append

Append in formdata Object shows empty.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        var formy = new FormData();
        formy.append("file", $("#file")[0].files[0]);
        console.log(formy);
});
});
</script>
</head>
<body>
<input id="file" type="file" size="40"><br><br>
<button>Send an HTTP POST request to a page and get the result back</button>

</body>
</html>

The output of the above code in the console log gives me

Formdata{}
append:function append()
arguments:null
caller:null
length:2
name:"append"

whereas console.log($("#file")[0].files[0]) gives me File {name: "document.pdf", lastModified: 1462959300000, lastModifiedDate: Wed May 11 2016 15:05:00 GMT+0530 (IST), webkitRelativePath: "", size: 5275…}

Why is append for formdata not working?

like image 822
Kanika Midha Avatar asked May 15 '16 07:05

Kanika Midha


2 Answers

Actually append IS WORKING. But you cannot log that way. To see your content, try this:

<script>
$(document).ready(function(){
    $("button").click(function(){
        var formy = new FormData();
        formy.append("file", $("#file")[0].files[0]);

    for(var pair of formy.entries()) {
      console.log(pair[0]+', '+pair[1]);
    }

});
});
</script>

I have added a screenshot of same code with 3 console statements. First is your files[0] object. Second is your pair[0] + ', ' + pair1. Third is your form object which will be empty as you are reporting.

Why and how is this happening can be read here. No point in duplicating theory here.

https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries

# I have provided description of console statements above

like image 195
Vikas Avatar answered Sep 30 '22 22:09

Vikas


A easier way to log formData is by using the .get() method.

console.log(formy.get("firstname"))
console.log(formy.get("lastname"))

As the case maybe.

like image 24
Lawrence Eagles Avatar answered Sep 29 '22 22:09

Lawrence Eagles