0

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;

});        
1
  • any error in your console? Commented Mar 20, 2013 at 4:38

2 Answers 2

1

As posted in the documentation, $.post accepts either a plain object or a string as its data argument. You cannot use FormData.

data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.

Sign up to request clarification or add additional context in comments.

1 Comment

How would I then turn a FormData object into a PlainObject or String?
1

jQuery calls $.param on the second argument to $.post (and others) if it is not a string. fd is not a string, but $.param on fd is invalid. If you want to use the raw fd value, you have to set processData to false in the ajax settings: http://api.jquery.com/jQuery.ajax/

$.ajax({
    ur: "/upload",
    data: fd,
    processData: false,
}).done(function (data) {
    console.log(data);
});

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.