Cristi Manole
Cristi Manole

Reputation: 31

Store jquery function on variable

I have this code in .js file:

$.getJSON('http://api.wipmania.com/jsonp?callback=?', function (data) {     
  if (data.address.country='spain') {
    var a="http://www.link1.com";
  } else { 
    var a="http://www.link2.com";
  }
  return a; 
});

var fan_page_url = data();

How can I store var a in var fan_page_url ?

Thank you very much.

Upvotes: 1

Views: 1509

Answers (3)

gloria
gloria

Reputation: 1

It's an old question on which I just stumbled (looking for something slightly different) but as answers did not seem to hit the nail on the head, I thought I'd add 2 cents: if you (op) had success with a variable that was hardcoded and set manually in config.js, that you were able to grab from start.js, why not simply:

  • keep the variable declared like you did in the global scope
  • assign it a default or null or empty value:

    var fan_page_url = null; // or
    var fan_page_url = ''; // or
    var fan_page_url = 'http://url_default'; // etc...
    
  • then update the global variable inside the json function:

    $.getJSON('http://api.wipmania.com/jsonp?callback=?', function(data) {
        if (data.address.country='spain') {
            fan_page_url = "http://url1";
        } else { 
            fan_page_url = "http://url2";
        }
    });
    
  • in your start.js page, you can always perform a check to see if the variable is set or not, or still carries it's default value or not and act accordingly...

It is likely that if it used to work with your normally, manually declared variable, it would work the same here as you would have changed nothing structurally, only would be updating the variable after the json response.

Answer posted for the posterity, it may help someone in the future.

Upvotes: 0

mgibsonbr
mgibsonbr

Reputation: 22007

You have two options: assigning the external variable directly, as depot suggested, or treating the $.getJSON return value as a Deferred:

$.when($.getJSON(...)).done(function(returnValue) {
    fan_page_url = returnValue;
});

The latter is useful in case you don't want to hardcode the variable you'll store the results (though in general it's not a problem, and the former option is easier/cleaner).

Upvotes: 0

Brian Ustas
Brian Ustas

Reputation: 65529

Try getting rid of a and assigning the links directly.

var fan_page_url;
$.getJSON('http://api.wipmania.com/jsonp?callback=?', function(data) {
    if (data.address.country = 'spain') {
        fan_page_url = "http://www.link1.com";
    } else {
        fan_page_url = "http://www.link2.com";
    }
});

Upvotes: 2

Related Questions