2

I seem to have run into a dead end.

I try to load the data using jQuery .get() but upon debugging, it shows the function is executed twice and as such the value from prodList is lost.

$.get(url, function (model) {
    prodList = $.parseJSON(model);
    alert(prodList);
});

alert(prodList);

In the first alert(), it shows the data returned from the server. But in the second alert() it shows empty string.

What am I doing wrong?

Nope
  • 22,147
  • 7
  • 47
  • 72
Bahdeng
  • 434
  • 8
  • 17
  • possible duplicate of [Variable doesn't get returned from AJAX function](http://stackoverflow.com/questions/12475269/variable-doesnt-get-returned-from-ajax-function) – Denys Séguret Apr 06 '13 at 07:42
  • What makes you think the function is executed twice, do you get four alerts? – Barmar Apr 06 '13 at 07:44
  • 2
    BTW, you can use `$.getJSON()` to save yourself a call to `$.parseJSON()` – Barmar Apr 06 '13 at 07:45

2 Answers2

5

The code you have shown is not indicating any issue with the execution.

Regarding the alerting of the values.

$.get() is an asynchronous execution, meaning that code execution continues after .get() has been kicked off.

The callback function you specified will not execute until the .get() is completed but the rest of the code continues until then.

Hence, the first alert shows you the value before the callback is executed and as such prodList is not populated yet.

The second alert then is displayed after the value is populated within the callback function.

$.get(url, function (model) {
    prodList = $.parseJSON(model);

    alert(prodList); // prodList is now populated
});

alert(prodList); // prodList here is alerted before it is populated

If you want to do something with prodList you either use it within the callback function itself or from the callback function call another function, passing prodList as an argument to process it there.

Nope
  • 22,147
  • 7
  • 47
  • 72
0

You get null value because:

prodlist is used after the get which is not

 async: false

Basically you need to be sure that the value you use first always happens before the second call.

So try not to use shorthand functions.

You may use this, many people avoid to use Sync Ajax, but few exception may be made depending on the situation:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType,
  async: false
});
radu florescu
  • 4,315
  • 10
  • 60
  • 92