Sergio Romero
Sergio Romero

Reputation: 6597

jQuery Ajax request returns null JSON only in Internet Explorer

I am making a jQuery Ajax request to an ASP.NET MVC controller using the jQuery Form plugin.

The call works fine, but when I'm parsing the expected JSON I get the expected result in Firefox, but I get null in Internet Explorer.

The Ajax call is like this:

var options = {
    iframe: true,
    dataType: 'json',
    success: function (result, status) {
        $.unblockUI();
        _editingEmail = false;

        if (result.Sent === true) {
            ... Do something
        }

        $("#messageSentResult").html("<div>" + result.Message + "</div>");
    },
    error: function (xhr, textStatus, errorThrown) {
        $.unblockUI();
        alert(textStatus);
    },
    beforeSubmit: function () {
        $.blockUI({
            message: '<h1>Processing...</h1>'
        });
    }
};

$('#myForm').ajaxForm(options);

This is my controller:

[HttpPost]
public FileUploadJsonResult MyMethod()
{
    ... Do something

    if(ValidationFails())
    {
        return new FileUploadJsonResult { Data = new { Sent = false, Message = "The operation was not successful." } };
    }

    return new FileUploadJsonResult { Data = new { Sent = true, Message = "The operation succeeded." } };
}

The FileUploadJsonResult class looks like this:

public override void ExecuteResult(ControllerContext context)
{
    this.ContentType = "text/html";
    context.HttpContext.Response.Write("<textarea>");
    base.ExecuteResult(context);
    context.HttpContext.Response.Write("</textarea>");
}

Upvotes: 1

Views: 2005

Answers (2)

zelmarou
zelmarou

Reputation: 231

You should check that your HTML page has no errors and no warnings and set the ajax configuration to:

$.ajaxSetup({ cache: false });

Upvotes: 2

Ender
Ender

Reputation: 15221

Have you tried setting cache: false in your options? By default, IE caches GET requests, which is what .ajax() uses, unless otherwise specified. This could be causing your problem.

EDIT:

Have you tried changing the ContentType to application/json? Like so:

public override void ExecuteResult(ControllerContext context)
{
    this.ContentType = "application/json";
    context.HttpContext.Response.Write("<textarea>");
    base.ExecuteResult(context);
    context.HttpContext.Response.Write("</textarea>");
}

Upvotes: 0

Related Questions