-1

I want to load a data that I got from Jquery.get into the variable in another function. The way I have tried is

function setPolicy(){
jQuery.get('/webapp/myProject/getPolicy', function(policy) {
    console.log(policy + " Policy"); //Just for Observation
}); }

and I want to load the data which is now stored in the Parameter Name "policy" into another variable in another function like the following

function loadAPI() {
var policy = setPolicy();
console.log("The policy is " + policy);

The result Shows in the console is just

The policy is

which mean the variable policy is not receive the data from the function.

What I would like to ask is How can I load the data from function "setPolicy" into the variable Name "policy" in another function calls "loadAPI" as a string? Thank you in advance.

Takumi
  • 355
  • 1
  • 7
  • 19
  • Does the `console.log(policy + " Policy");` output the policy data sent to the $.get callback? – Mark Erasmus Aug 29 '13 at 11:38
  • simple answer, you can't do it like that – Arun P Johny Aug 29 '13 at 11:40
  • @MarkErasmus the console Shows the policy that I got from the URL correctly but I can't assign it to the variable in another function. – Takumi Aug 29 '13 at 11:41
  • The $.get is an asynchronous operation, so the line `console.log("The policy is " + policy);` is executing before the callback is executed, hence the policy is null. – Mark Erasmus Aug 29 '13 at 11:50
  • But the policy of function setPolicy() shows in the console is correct while the policy in loadAPI() function is null. Even I return the policy after the $.get execution but seem like it is not received by variable policy in loadAPI() function. Why? – Takumi Aug 29 '13 at 12:00

1 Answers1

0

You need to return the fetched value. Try to add this stmt in your code -

$.get('URL', function(data) {
$('.result').html(data);
return data;
});
Christina
  • 1
  • 4
  • It is not work. The Parameter "data" received a correct data from URL and the value when it return still correct but the variable in another function still undefined – Takumi Aug 29 '13 at 11:51
  • Strange.! May be variable policy is declared somewhere else also in code ? OR instead of calling func, directly write down your code can help? – Christina Aug 29 '13 at 11:54
  • The variable policy is not declared in anywhere. I still able to received the policy from Server side and print out in the console just within the function that execute the URL. I tried to pass it to another function by your Suggestion but it is not work. I also tried to write down the code to the variable but I think it is not good to do so. What I have tried is something like 'var policy = jQuery.get('URL', function(data))'. and it is work...but weird coding in my opinion. I think we should be able to call it from another function. Due to my experience on JavaScript, I do not know how... – Takumi Aug 29 '13 at 12:01