Question

If I have a form:

<form id="myAjaxUploadForm" enctype="multipart/form-data" method="post" action="/upload">
<input type="file" id="my_img_upload_input" name="my_image">
<input type="submit" value="upload">
</form>

And then I make a FormData() object within a jQuery ajax request:

var myShinyData = new FormData($("#myAjaxUploadForm")[0]);

1) What data structure is myShinyData? An array?

2) If so, after instantiation, what key:values does that array contain (using the example above)?

3) I used the above instantiation code after viewing several demo's, and it works, but what does the 0 index refer to? The first input field in the form?

4) If I then appended a key:value with:

myShinyData.append("username", username);

How could I immediately alert the username key's value? alert(myShinyData.username) ?

5) Are there any other key:value's that are available upon instantiation by default, eg the filename and filesize, and if so how can I access and alert them?

The above information is probably within the following excellent documents, but I haven't been able to fully extract and comprehend it yet:

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

Was it helpful?

Solution

1) myShinyData would be a JavaScript object, which is why it can be dereferenced using object noation (. or ["key"]).

2) After instantiation, the object would contain a key:value pair for each input field within the form, where the key would be the name of the field and the value would be the value.

3) The [0] on $("#myAjaxUploadForm") references the actual form on the page itself. When you use jQuery to select an object, you get back a jQuery object. A jQuery object is a wrapper around a normal DOM object to expose additional methods that can be executed against it.

$("#myAjaxUploadForm")[0] === document.getElementById("myAjaxUploadForm")

4) Yes, if you append a new key to the FormData, you can access it using dot notation or array notation:

myShinyData.username
myShinyData["username"]

5) The information available by default would be what is in the form; I assume this would include the file name, but that may require some parsing. Any other information would need to be obtained programmatically, either using the information you already have, or some other means.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top