0

my code in a javascript file:

$.getJSON('assets/jsons/fields.json', function(fieldsData){
          fieldsdata = fieldsData;
    });
    $.getJSON('assets/jsons/rulesjs.json', function(rulesData){
          rules = rulesData;
    });

    conditions.conditionsBuilder({
      fields: fieldsdata,
      data: rules

    });

with a breakpoint at fields:fieldsdata, it works fine. It fetches data from the respective .json file and shows data Else it doesn't show any thing. Things I have tried: 1. I tried rearranging the javascript file declaration in index.html. No success 2. I tried using global variables. 3. I tried putting GETJSON's in a different function and call it before assignment.

I know I am missing something simple but could not figure out. Plz help. Thanks

1 Answers1

0

$.getJSON() is asynchronous. That means that the $.getJSON() function finishes executing and then sometime LATER, the callback is called. It does not wait for the request to finish before the following code is run. If you want to use your two ajax results, you have to know when both ajax functions are done. There are multiple ways to do that.

One way is to sequence the two operations and only use the result in the final callback:

$.getJSON('assets/jsons/fields.json', function(fieldsData){
    $.getJSON('assets/jsons/rulesjs.json', function(rulesData){
         conditions.conditionsBuilder({
             fields: fieldsData,
             data: rulesData
         });
    });
});

Another way is to launch the two requests in parallel and use jQuery promises to know when both are done.

$.when($.getJSON('assets/jsons/fields.json', $.getJSON('assets/jsons/rulesjs.json'))
     .then(function(fields, rules) {
         conditions.conditionsBuilder({fields: fields[0], data: rules[0]});
     });

Launching the requests in parallel will likely finish in a shorter amount of time.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Aye aye sir, It is working. Can you tell me which topics should I read to know Javascript better. I guess asynchronous functions is one. Anyways, thanks a million for the fix. Indebted. Named your handle aptly a "Friend" in need – FrontEnd-ra Nov 05 '14 at 23:35
  • @user3878332 - study every aspect of this answer: http://stackoverflow.com/a/14220323/816620. Beyond that, there are thousands of great Javascript resources. [This book](http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742) is considered a very good resource. – jfriend00 Nov 05 '14 at 23:37