Nick Heidke
Nick Heidke

Reputation: 2847

jQuery Ajax Success nor Fail methods hit

I've got the following code below which is supposed to make a call to the controller when a link is clicked. The controller is getting called successfully, but the only method on the javascript side that is hit is always which displays a pop up stating "undefined".

Adding Method to Link

$('.retrieveTeam').click(function () {
        _getData($(this).data("teamkey"));
    });

jQuery AJAX Call

function _getData(postdata) {
    var request = $.ajax({
        url: 'RetrieveTeam',
        type: 'POST',
        data: JSON.stringify({ TeamKey: "331.l.542488.t.1" }),
        datatype: JSON,
        contentType: "application/json"
    });
    request.success = function (result) {
        alert(result);
    }
    request.error = function (result, xh) {
        alert("error");
    }
    request.fail = function () {
        alert("failure");
    }
    request.always = function (result) {
        alert(result);
    }
}

Controller

    [HttpPost]
    public JsonResult RetrieveTeam(string TeamKey)
    {
        List<Team> objTeams = (List<Team>)Session["Teams"];

        Team objTeam = objTeams.Where(x => x.TeamKey == TeamKey).FirstOrDefault();

        objTeam.AddPlayer(new FootballPlayer(new Position("QB", "QB", "QB"), "Brett Favre", "QB"));

        return Json(objTeam);
    }

Upvotes: 1

Views: 681

Answers (1)

Etheryte
Etheryte

Reputation: 25310

You're using jQuery 2.1.1. Reading the manual page for $.ajax we can see that:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

In your code,

request.success = ...

should be replaced with

request.done(...)

and .fail = with .error() as well. Also, fix your dataType.
All together this brings us to:

function _getData(postdata) {
    $.ajax({
        url: 'RetrieveTeam',
        type: 'POST',
        data: JSON.stringify({ TeamKey: "331.l.542488.t.1" }),
        datatype: "json",
        contentType: "application/json"
    }).done(function (foo) {

    }).fail(function (foo) {

    }).always(function (foo) {

    });
}

Upvotes: 4

Related Questions