jQuery Form Plugin: enctype:multipart/form-data and file-upload - no JSON returning?

matt picture matt · Feb 20, 2012 · Viewed 8.9k times · Source

weird problem or bug. I'm using the jQuery Form Plugin and it works fine everywhere accept on one form where I have a single file-upload with enctype:multipart/form-data on the form. On this form I'm facing two weird things …

  1. the JSON object that is returned from the server is empty!
  2. In Opera the Submit-button even triggers a file-download!

However this occurs only if I leave the enctype:multipart/form-data and the input type="file" in the form. Without it everything works fine and the JSON Object is returned correctly - and there is no download in Opera.

HTML:

<form accept-charset="UTF-8" action="/ajax/profiledetails" id="profileAboutMeForm" method="post" novalidate="novalidate" encoding="multipart/form-data" enctype="multipart/form-data">

    ...

    <p class="rel avatarUpload">
        <label class="label" for="profileAvatar">Choose Avatar</label>
        <img class="profileAvatar avatar30" src="" alt="user">
        <input class="fileUpload br3" id="profileAvatar" name="profile[avatar]" type="file">
    </p>

    ...

</form>

jQuery:

$(formId).ajaxSubmit({
        type: "POST",
        cache: false,
        resetForm: reset,
        dataType: "text json",
        success: function(jsonObject, status) {

            console.log("status + ", jsonObject.status: "+ jsonObject.status + ", jsonObject.data: " + jsonObject.data);

Any idea what could cause that? How I could fix that?

Thank's in advance.

edit:

What I never tried though was to just log the object itself and here it turns out that in this case (only if the file-input and enctype is set) the jsonObject is a STRING and not an object.

if (typeof jsonObject == 'string')
        console.log('yes, it's a string'); //yes, it's a string
        jsonObject = JSON.parse(jsonObject);

console.log(jsonObject);

So, this means I have a JSObject again in my javascript and this fixes my first problem, however the opera-bug still remains! Any ideas?

Answer

Jkleg picture Jkleg · Feb 20, 2012

Just as a starting point, I assume you've read the documentation about this on the plugins page at http://jquery.malsup.com/form/#file-upload? You won't get access to the JSON within ajaxSubmit() because the response is actually written to a hidden iframe used for the upload.

"Since it is not possible to upload files using the browser's XMLHttpRequest object, the Form Plugin uses a hidden iframe element to help with the task. This is a common technique, but it has inherent limitations. The iframe element is used as the target of the form's submit operation which means that the server response is written to the iframe. This is fine if the response type is HTML or XML, but doesn't work as well if the response type is script or JSON, both of which often contain characters that need to be repesented using entity references when found in HTML markup.

To account for the challenges of script and JSON responses, the Form Plugin allows these responses to be embedded in a textarea element and it is recommended that you do so for these response types when used in conjuction with file uploads. Please note, however, that if there is no file input in the form then the request uses normal XHR to submit the form (not an iframe). This puts the burden on your server code to know when to use a textarea and when not to. If you like, you can use the iframe option of the plugin to force it to always use an iframe mode and then your server can always embed the response in a textarea."

Here is the code he uses on the examples page:

$('#uploadForm').ajaxForm({
  beforeSubmit: function(a,f,o) {
    o.dataType = $('#uploadResponseType')[0].value;
    $('#uploadOutput').html('Submitting...');
  },
  success: function(data) {
    var $out = $('#uploadOutput');
    $out.html('Form success handler received: <strong>' + typeof data + '</strong>');
    if (typeof data == 'object' && data.nodeType)
      data = elementToString(data.documentElement, true);
    else if (typeof data == 'object')
      data = objToString(data);
    $out.append('<div><pre>'+ data +'</pre></div>');
  }
});

The success method is what matters for you here...notice that he is writing the return data to the page for debugging purposes.