2

I cant seem to get this for the life of me. I cant access the variable "json" after I calll the getJson2 function. I get my json dynamically through a php script, and that works. But then its gone. there is a sample that I use as a guide at The InfoVis examples where the json is embedded in the init function. i am trying to get it there dynamically.

<script language="javascript" type="text/javascript">
var labelType, useGradients, nativeTextSupport,animate,json;
function getJson2()
{
  var cd = getParameterByName("code");
  $.get("tasks.php?code="+cd, function(data){
    return data;
  })
 };
function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

(function() {
  var ua = navigator.userAgent,
      iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
      typeOfCanvas = typeof HTMLCanvasElement,
      nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
      textSupport = nativeCanvasSupport 
        && (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
  //I'm setting this based on the fact that ExCanvas provides text support for IE
  //and that as of today iPhone/iPad current text support is lame
  labelType = (!nativeCanvasSupport || (textSupport && !iStuff))? 'Native' : 'HTML';
  nativeTextSupport = labelType == 'Native';
  useGradients = nativeCanvasSupport;
  animate = !(iStuff || !nativeCanvasSupport);
})();
debugger;
var Log = {
  elem: false,
  write: function(text){
    if (!this.elem) 
      this.elem = document.getElementById('log');
    this.elem.innerHTML = text;
    debugger;
    this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px';
  }
};  
function init(){
json = getJson2();
    //init data
var st = new $jit.ST({  
    //id of viz container element  
    injectInto: 'infovis',  
    //set duration for the animation  
    duration: 800,  
    //set animation transition type  ..................
3
  • You can't access it? You're not accessing anywhere.
    – phant0m
    Dec 12, 2012 at 18:40
  • when do you call getJson2?
    – Christophe
    Dec 12, 2012 at 18:42
  • $.get is asynchronous, you can't return from it's callback without using Deferred objects.
    – jbabey
    Dec 12, 2012 at 18:44

4 Answers 4

2
function getJson2()
{
  var cd = getParameterByName("code");
  $.get("tasks.php?code="+cd, function(data){
    return data;
  })
};

getJson2() doesn't return anything. The callback function to $.get() returns something, but nothing is listening for that return.

It sounds like you want synchronous loading instead. $.get() is just shorthand for this $.ajax() call: (See docs)

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

And $.ajax() supports more features, like setting async to false.

$.ajax({
  url: "tasks.php?code="+cd,
  async: false,
  dataType: 'json',
  success: function(data) {
    // data !
  }
});

Which means, getJson2 then becomes:

function getJson2()
{
  var cd = getParameterByName("code");
  var jsonData;

  $.ajax({
    url: "tasks.php?code="+cd,
    async: false,
    dataType: 'json',
    success: function(data) {
      jsonData = data;
    }
  });

  return jsonData;
};

var myJsonData = getJson2();

Or still use $.get async style, and use callbacks instead.

function getJson2(callback)
{
  var cd = getParameterByName("code");
  $.get("tasks.php?code="+cd, function(data){
    callback(data);
  });
};

getJson2(function(data) {
  // do stuff now that json data is loaded and ready
});
1

The $.get call is asynchronous. By the time you call return data;, the function has already long since returned. Create a variable outside of your function's scope, then in the $.get callback handler, assign data to that variable.

var json;

function getJson2(){
    // ...
    $.get(...., function(response){
        json = response;
    }
});

Alternatively, you could do a sychronous Ajax call, in which case returning your data would work (but of course would block script execution until the response was recieved). To accomplish this, see the asynch argument to jQuerys $.ajax function.

2
  • While correct about what is happening, the solution will not help.
    – jbabey
    Dec 12, 2012 at 18:43
  • @jbabey I'm not going to rewrite the whole script for the op. This is fundamentally what is wrong about the current approach.
    – Madbreaks
    Dec 12, 2012 at 18:45
1

A jQuery $.get call is asynchronous and actually returns a promise, not the data itself.

An elegant way to deal with this is to use the then() method:

$.get(...).then(function(data){...});

Alternately, change your ajax settings to make the call synchronous.

4
  • 1
    Do NOT make the ajax call synchronous. jQuery is deprecating that functionality and it locks up the web page.
    – jfriend00
    Dec 12, 2012 at 18:54
  • 1
    @jfriend00 There will always be use cases for synchronous AJAX. jQuery may (?) deprecate it, but it will of course remain possible via pure JS.
    – Madbreaks
    Dec 12, 2012 at 18:55
  • @jfriend00 point taken, and obviously this was not my recommendation. Where did you see that btw?
    – Christophe
    Dec 12, 2012 at 18:57
  • @Madbreaks - name a good use case for synchronous ajax that works better for the user experience. There are lazy developers who don't want to recode properly to do it asynchronously, but I've never encountered a case where synchronous ajax is a better option for the user.
    – jfriend00
    Dec 12, 2012 at 19:06
0
$.get("tasks.php?code="+cd, function(data){
    return data;
  })

$.get is asynchroneous. So your value is never returned. You would have to create a callback.

The same question appears here: Return $.get data in a function using jQuery

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.