0

I was wondering if it was possible to gain access to returned JSON data outside of the JQuery getJSON method.. something like this..

var price = "";
$.getJSON("../JSONDeliveryPrice", null, function (data) {
  price = eval(data.price);
});
console.log(price);

This doesn't work tho, is there another way to gain access to price outside of that block?

qiao
  • 17,941
  • 6
  • 57
  • 46
CallumVass
  • 11,288
  • 26
  • 84
  • 154
  • 1
    You need to use syncronous request. Here is great answer hot to do it: http://stackoverflow.com/questions/933713/is-there-a-version-of-getjson-that-doesnt-use-a-call-back – Samich Jan 17 '12 at 08:36
  • Making the call synchronous is backwards. The code that handles the response must be in (or called in) the [continuation passed to `getJSON`](http://stackoverflow.com/questions/31129/how-can-i-return-a-variable-from-a-getjson-function). – outis Jan 18 '12 at 06:43

3 Answers3

0
var price = "";
$.getJSON("../JSONDeliveryPrice", null, function (data) {
    price = eval(data.price);
    console.log(price); // e.g. "$120", comes later
    doSomething(data); // uses the JSON data
});
console.log(price); // "", comes first
Aram Kocharyan
  • 20,165
  • 11
  • 81
  • 96
  • It will not work because your `console.log(price);` will be invoked mutch earlier then `getJSON` callback function. – Samich Jan 17 '12 at 08:39
0

It's not that you can't access the data outside of the callback function, it's just that the console.log() statement is executed prior to the callback being executed, so at the time the log is executed, the variable is still empty.

I made a fiddle to illustrate this based on the example on the jQuery site

danwellman
  • 9,068
  • 8
  • 60
  • 88
0

I was just researching a similar issue when I found this question: Is there a version of $getJSON that doesn't use a call back?

I believe you'll need to make your call synchronously as well.

Community
  • 1
  • 1
Mattio
  • 2,014
  • 3
  • 24
  • 37