1

I have a function that calls a JSON string from another URL. The JSON is coming through fine and behaving as I want it to. The variable 'procode' is what I want to use outside the function, but I dont know how to pass the value of 'procode' up and out of the function completely, so I can use it on a global scale.

function(){
     $.get('http://url-here/api/product', function(data) {
         var rawcode = JSON.parse(data);
         var procode = '"products":' + rawcode;
     }, 'text');
}

Thanks in advance for any help :)

Visiophobia
  • 153
  • 3
  • 8

2 Answers2

3

you need to set global variable to access it outside.Something like this:

var rawcode="";
var procode="";
function(){
 $.get('http://url-here/api/product', function(data) {
     rawcode = JSON.parse(data);
     procode = '"products":' + rawcode;
    }, 'text');
 }
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • Hi Milind, thanks for the quick response! If i put an `alert(procode);` inside the function after the procode variable itself, it gives me an alert with the exact code I want to use, but if I follow your suggestion and put the `alert(procode);` after the function, it just returns an empty alert box. Where am I going wrong? – Visiophobia Feb 11 '14 at 11:10
  • Visiophobia, `$.get()` is of Deferred type. You have to wait for `procode` to be filled by the ajax call. – Talha Ahmed Khan Feb 11 '14 at 11:13
  • @Visiophobia:This is beacause code is getting executed before the response is get through jquery get request. To get modified value , you either need to write success function for get request or setTimeout and execute the code. FYI, using setTimeout is bad practise because you would not come to know about get success on different environment. – Milind Anantwar Feb 11 '14 at 11:46
0
window.procode="";
var myFunction = function(){
    var ajaxCall = $.get('http://url-here/api/product', function(data) {
       var rawcode = JSON.parse(data);
       window.procode= '"products":' + rawcode;
    }, 'text');

    $.when(ajaxCall).done(function(){
       alert(window.procode);
    });
};
Talha Ahmed Khan
  • 15,043
  • 10
  • 42
  • 49