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):
CALLED WITHOUT THE FILE UPLOAD (WORKS):
WHAT FAIL LOOKS LIKE IN IE:
WHAT FAIL LOOKS LIKE IN FF:
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"!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With