jQuery ajaxForm returning .json file

心不动则不痛 提交于 2019-11-30 09:03:34

To prevent browser to trigger download of .json file set Content-type header to "text/html".

PHP:

header("Content-type: text/html");

ASP.NET MVC:

return Json(obj, "text/html");

In javascript you need to parse text result, like this:

$(".addform").ajaxSubmit({
            url: "file.php",
            type: "POST",
            dataType: "text",
            iframe: true,
            success: function (text) {
                var data = $.parseJSON(text);
            },
            error: function (xmlRequest, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });

Works perfectly.

This plugin will allow you to submit MultiPart Forms using ajax.

If you want to use the Ajax 'success:' option you have to submit the form using ajax. Currently you are using the submit() function which basically just submits the form in the traditional way. The fact that you are able to see the json data as a downloaded file or in your browsers means that this is happening.

You need to use that plugin(if you need the multipart function - otherwise just use the regular Ajax function)

With the plugin, you would use it like this :

$("#SubmitButton").click(function(){


$.ajaxFileUpload(
    {
    url:serverurl,
    secureuri:false,
    fileElementId:elementId,
    dataType: 'json',
    success: function (data, status)
    {
  /* show success message */
    },
    error: function (data, status, e)
    {
  /* handle error */
    }
});

});

If you want to do it without the file upload, there is an easier way to do it.

$("#SubmitButton").click(function(){

$.post('YOUR_URL', $("#FormName").serialize(), function(data){
     alert(data.name); // John
   }, "json");  //specify return data is going to be json


    });

Though not exactly what I was aiming to solve, I was able to come to a slightly different solution that suited my needs!

As ajax file uploads are done through iframes, the issue was that after the iframe loaded the .json file, it was interpreted by Firefox as a download and a download prompt was opened. I am pretty sure I could have played with some server settings to prevent this, but I've already sunk enough time into this.

So what I did was rendered the output as text instead of json because I was only really fishing for one id number anyway. My code now looks like:

$(document).ready(function() {
  $('#continue-upload').click(function() {
    $('#new_stem').ajaxSubmit({
      dataType: 'text', //'json',
      success: formSuccess
    });
  });
});

The id number I needed also came wrapped in pre tags, so I needed to strip those off in my results function as well.

This does what I want it to now, woo!

Actually the ajaxSubmit code for that plugin is slightly hacky. To make ajaxSubmit work (at time of writing) your server must return JSON data as content-type=text/html. The plugin will automatically pull off the <\pre> tags etc (see source). I guess when they were trying to get the hidden iframe to pull json back they decided to treat json a text and parse it off the iframe.

Sounds like as if its Content-Type response header is incorrect and thus the browser doesn't know what to do with it. It should be application/json. You can use the Firebug's Net panel to detemine the actual response headers.

Are you cancelling the default action of the submit event? It sounds like the form is actually being submitted (in the classical sense – in other words, Firefox is actually navigating to the page specified in the form's action).

Maybe it helps

$('#cpFileUpload').ajaxForm({
        dataType: 'html',           
        success: function(data) {           
            eval(data);                 
            if (data.result == false) {
                alert('error on server side');
            } else {                
                // do what you want
            }
        }       
    }); 

And on server side the output must be like this (only this output or without any other text inside body tag)

var data = {result: true, html: 'ok'}

Not so nice, but working

Easy way:

$('#new_stem').ajaxForm({ dataType: 'text', complete: function(xhr) { data = JSON.parse(xhr.responseText); } });

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!