-7

I have the following code inside a button-click-function

var ItemID2;

$.get("http://localhost/tddd27/index.php/json/Products?ItemName="+thisID, 
          function(data){
             ItemID2=data[0].ItemID;
            },"json");

console.log(ItemID2);

after I click the button I see in the console that ItemID2 is undefined. If I use console.log(data[0].ItemID) inside the get-function I see the correct value. I think that the problem is that the execution of the function continues but Ajax has not yet retrieve the value of ItemID2. Any idea how can I fix that?

Michael
  • 3,982
  • 4
  • 30
  • 46
Avraam Mavridis
  • 8,698
  • 19
  • 79
  • 133

3 Answers3

2

I think that the problem is that the execution of the function continues but Ajax has not yet retrieve the value of ItemID2.

You are right, it's an asynchronous function. You have to resume your program flow to the request's callback.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
2

A-JAX is A-synchronous.

That is why there is a callback function.

Naftali
  • 144,921
  • 39
  • 244
  • 303
2

Simple:

var ItemID2;

$.get("http://localhost/tddd27/index.php/json/Products?ItemName="+thisID, 
          function(data){
             ItemID2=data[0].ItemID;
             console.log(ItemID2);
            },"json");
A. Wolff
  • 74,033
  • 9
  • 94
  • 155