0

Hello I have a problem storing my json in a global variable, what I want is to do first all my ajax request then store each of the returned data to a global variable, but it seems it's not working correctly? Can Any help me to my problem? Thanks. :)

var series;

function columnChart(container)
{
url = base_url+"/codeigniter/index.php/AssistanceMonitoringModule/assistanceMonitoring/getSeries";

 $.ajax(
            {
            type: "GET",
            url: url,
            success: function(data){
                series = data;
            },
            dataType: "json",
            error: function (xhr, ajaxOptions, thrownError) {
                alert("XHR:"+xhr.status+"Error:"+thrownError);
              }

            });

 callColumnChart(container,series);

}

akoDwin
  • 139
  • 2
  • 2
  • 14
  • A hint: your title already has an important keyword: "after". `callColumnChart` is called **before** the ajax request is completed – zerkms May 26 '14 at 03:03
  • hmmm. Yeah, but I want to do all my ajax before passing the resulted data to the callColumnChart. That's why I call my callColumnChart after the ajax request. – akoDwin May 26 '14 at 03:06
  • It seems you don't understand async behavior and Ajax yet. Have a look at the duplicate question, it should help you understand the overall problem better. – Felix Kling May 26 '14 at 03:08
  • aw. so i can't ready first all my data before calling a specific function? :/ – akoDwin May 26 '14 at 03:11
  • Of course you can. You have to call the specific function inside the Ajax callback. The callback is called when your data is ready. – Felix Kling May 26 '14 at 05:21

1 Answers1

2

You are using the variable too soon. The Ajax request will not be completed when you call callColumnChart. Move it into the ajax callback.

$.ajax(
            {
            type: "GET",
            url: url,
            success: function(data){
                series = data;
                callColumnChart(container,series);
            },
            dataType: "json",
            error: function (xhr, ajaxOptions, thrownError) {
                alert("XHR:"+xhr.status+"Error:"+thrownError);
              }

            });
TGH
  • 38,769
  • 12
  • 102
  • 135
  • 1
    "The Ajax call may not be completed when you call it" --- it's not uncertain in this case. It must be: the ajax request will **NEVER** be completed – zerkms May 26 '14 at 03:04
  • 1
    nope. It's a single threaded environment. So the callback is guaranteed to be called after that – zerkms May 26 '14 at 03:06
  • 1
    The response can only be processed after the current execution terminates. – Felix Kling May 26 '14 at 03:07
  • im nuts, I don't know what to do. :/ How can I process all the data before passing it in callColumnChart. :( – akoDwin May 26 '14 at 03:41
  • 1
    @akoDwin: By calling `callColumnChart` inside the success callback. I don't understand why this is a problem for you. – Felix Kling May 26 '14 at 17:28