tl;dr: the two scripts below are not identical although I believe them to be. Why?
I'll give you some background information about this post. I'm trying to build an image uploading form that makes AJAX requests to create a dynamic upload page. Since I learned about HTML5's File API, I'm trying to use it in an AJAX request. I built my own instance by following some nice examples on MDN. My working script uses straight JS for the AJAX request, but I tried building a version that uses jQuery instead. My question is, why won't the jQuery version work properly? As far as I can tell, it's a straight port from JS xhr-style AJAX to jQuery-style AJAX. (The point of this question is to gain an academic understanding of jQuery's AJAX API; since I already have a working script, my practical needs have been fulfilled)
Here is the working Javascript AJAX request:
$("form").submit(function(){
var file = $("input:file").get(0).files[0];
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", "/upload", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
fd.append('img', file);
xhr.send(fd);
return false;
});
And the non-working jQuery version:
$("form").submit(function(){
var fd = new FormData();
var file = $("input:file").get(0).files[0];
fd.append('img', file);
$.post("/upload", fd, function(data){
alert(data);
});
return false;
});