Siraj Hussain
Siraj Hussain

Reputation: 874

$.getJSON is not calling call back function

call back in not being called.

function GetTrainingResults(id,callback){
    $.getJSON("/dashboard/GetTrainingResults/", {'id':id}, callback);
}
GetTrainingResults('id',function(result){
    alert(result);
});

and code behind is

 public ActionResult GetTrainingResults(int id)
    {
        string test = "You are there.";
        return Json(test, JsonRequestBehavior.AllowGet);
    }

Or suggest and another way. Task in to call controller method and wait for method response in javascript.

Thanks

Upvotes: 3

Views: 1821

Answers (3)

Tom Riley
Tom Riley

Reputation: 1722

Check that your request is returning successfully, the ajax shorthand functions only call the callback if the request is successful (ie status code 200 and of the right data type, ie json). Try the full .ajax jquery function and see whats going on under the hood.

.getJSON() is equivient too

$.ajax({
 dataType: "json",
 url: url,
 data: data,
 success: success
});

so it might be hitting error: due to the data type.

Source http://api.jquery.com/jQuery.getJSON/

Upvotes: 0

James Wright
James Wright

Reputation: 3010

If you use jQuery.ajax, you'll at least be able to see the error being returned by the server:

function getTrainingResults(id, callback) {
    $.ajax({
        url: "/dashboard/GetTrainingResults/",
        data: {id: id},
        success: function(data) {
            callback(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
            callback(errorThrown);
        }
    });
}

Upvotes: 3

Mathew Thompson
Mathew Thompson

Reputation: 56429

id in your Action method takes an int, yet you're passing it a string of 'id' in your JS. Either change your JS or you action method so that the types match.

Upvotes: 1

Related Questions