baron
baron

Reputation: 11181

Success callback not working properly for $.ajax

I have a problem which is similar to this stackoverflow

I am sending a list of selected objects to an "Update" method. That works fine, the problem is on the success callback. It does not happen for some reason. The page just sort of blinks once. In firebug's net tab I can see call to the url. The controller returns bool so in the Response I just have true. But obviously what I want to do is update the page based on that bool. This is MVC2 project-not sure if this has to do with it.

$.ajax({
    url: "/Update/UpdateAll",
    dataType: 'json',
    type: "POST",
    data: { selected: selected, statusID: statusID },
    success: function (result) {
        if (result) {
            alert('all successful');
            $('#resultsFromUpdate').html("Success");
        }
        else {
            alert('no deal');
            $('#resultsFromUpdate').html("Fail");
        }
    }
});

and UpdateAll controller method:

public bool UpdateAll(string selected, string statusID)
{
...
> update some things
> return true if fine
> return fasle if not
...
}

This is exactly the point of using AJAX, not requiring a page post...So what am I doing wrong ?

Upvotes: 2

Views: 5048

Answers (3)

Andrew Shepherd
Andrew Shepherd

Reputation: 45252

This is a good place to delve into the arsenal of free debugging tools web developers have.

Note that Chrome, Firefox and IE9 all provide developer tools (just press F12 for IE9). These allow you to step through the code and observe the variables that returned.

You can also use fiddler to examine the content passed between the browser and visual studio.


Note that JSON-enabled WCF services written in ASP.NET 3.5 return an object where the return value is a data member d.

You can try this:

$.ajax({
    url: "/Update/UpdateAll",
    dataType: 'json',
    type: "POST",
    data: { selected: selected, statusID: statusID },
    success: function (result) {
        /* NOTE: Not checking result, but result.d */
        if (result.d) {
            alert('all successful');
            $('#resultsFromUpdate').html("Success");
        }
        else {
            alert('no deal');
            $('#resultsFromUpdate').html("Fail");
        }
    }
});

If I guessed it right I'm buying a lottery ticket :-)

Upvotes: 2

pcjuzer
pcjuzer

Reputation: 2824

My advice is to use Firebug or other Javascript debugging tool and/or specify 'error' callback at least with an 'alert' in it besides 'success'. Maybe MIME type sent by the server is not matched, or there can be some other reason.

Upvotes: 0

Tieson T.
Tieson T.

Reputation: 21201

Should really have a JsonResult as your return type, as you specified "json" as what the $.ajax method should expect. Also, the $.post method is usually easier to use.

Upvotes: 4

Related Questions