Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multipart Form POST Causes Firefox To Prompt JSON Save

I have a problem that happens in IE 8 and Firefox 6.0 but not Chrome 17.0.9. When I post frmMain below I'm sending it to a test page that just returns a simple JSON string with ContentType: application/json; charset=utf-8. The problem is that IE and FF will prompt me to save the JSON that is returned from the server and not hit the success method in my jquery code. But strangely, if I omit the <input name='File_1' type='file' /> on the posted form then IE and FF do not prompt me to save my JSON and my jquery success code fires.

So it seems that the posted content has a bearing (in IE and FF) on how the browser reacts to the returned payload. Through Fiddler I've verified that in each case the returned payload is exactly the same.

Any ideas?

SOLUTION FOUND: See my answer below. From what I can gather "text/html" is the best cross-browser content type to return when doing jquery/ajax/json.

CODE

<script>
     $(function () {
         $('#btnSave').click(function () {
             $('#frmMain').ajaxSubmit({
                 success: function (data, statusText, xhr, $form) {
                     alert('test success');
                 },
                 fail: function (data, statusText, xhr, $form) {
                     alert('test fail');
                 }
             });
         });
     });
</script>
<body>
     <form id='frmMain' action='/test' method='post'>
              <!--Omit the file input below to make it work-->
          file: <input name='File_1' type='file' /><br />

          name: <input name='json' value='{"id":5}' /><br />

          <input type='button' id='btnSave' value='Save' />
     </form>
</body>

CALLED WITH THE FILE UPLOAD (CAUSES FAIL): enter image description here

CALLED WITHOUT THE FILE UPLOAD (WORKS): enter image description here

WHAT FAIL LOOKS LIKE IN IE: enter image description here

WHAT FAIL LOOKS LIKE IN FF: enter image description here

like image 378
sisdog Avatar asked Apr 06 '12 14:04

sisdog


1 Answers

After a TON of trial and error I ran across this SO post where @ItsJason recommended setting the server's ContentType to "text/html". That solved the problem and my jQuery code still recognized the returned payload as JSON when it called my callback method. so lesson learned: for total cross-browser compatibility when returning JSON to jquery during an ajax postback, don't use "application/json", use "text/html"!!

like image 74
sisdog Avatar answered Oct 17 '22 13:10

sisdog