Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getJSON callback not firing

I'm making the call using the following script which is called on click of an anchor tag

function GetToken(videoId) {
  debugger;
  var json = $.getJSON("/Vod/RequestAccessToken/" + videoId, function(result) {
    alert("token recieved: " + result.token);
  });
}

In the server application I receive the call so I know it is a valid URL, but the callback is not being invoked. If i set though the jquery code (f11/f10) the callback is called??!!!?

Server returns results from MVC application in the form of a class

// function called
public JsonResult RequestAccessToken(int id)
{
    Token t = new Token();
    t.MasterId = Guid.NewGuid();
    var result = new TokenResult(t.MasterId);
    return this.Json(result, JsonRequestBehavior.AllowGet);
}

// class returned
public class TokenResult
{
    public TokenResult() { }
    public TokenResult(Guid g) { token = g.ToString(); }
    public string token = null;
}

When I access the url via browser result =

{
  "token":"c877453e-739d-4883-9310-91ddd707d6af"
}
like image 702
Marty Trenouth Avatar asked Apr 26 '10 20:04

Marty Trenouth


2 Answers

If your result is not successful, that callback won't fire, this is usually due to invalid JSON being returned. To give it a test, you can use the long form of $.getJSON, like this so you can see the error:

$.ajax({
  url: url,
  dataType: 'json',
  success: function(result){
    alert("token recieved: " + result.token);
  },
  error: function(request, textStatus, errorThrown) {
    alert(textStatus);
  },
  complete: function(request, textStatus) { //for additional info
    alert(request.responseText);
    alert(textStatus);
  }
});

If it is a JSON/parser error, you can take your response and see what's wrong with JSONLint, here: http://www.jsonlint.com/

like image 109
Nick Craver Avatar answered Sep 24 '22 15:09

Nick Craver


A likely bet is that you're not returning valid JSON. The jQuery docs note that, "As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently." Does the JSON text you're serving pass JSON Lint? You may also want to switch (at least temporarily) to jQuery.ajax. It allows more error handling. Something like:

$.ajax({
  url: "/Vod/RequestAccessToken/"+videoId,
  dataType: 'json',
  error: function(xhr, textStatus, errorThrown){

        },
  success: function(result){
            alert("token recieved: " + result.token);
        }
});
like image 45
Matthew Flaschen Avatar answered Sep 23 '22 15:09

Matthew Flaschen