Search code examples
javascriptjqueryjsontimeline.js

How to return json from google script url


I want to get json value in timeline_json of the following line

          window.timeline = new VCO.Timeline('timeline-embed', new VCO.TimelineConfig(timeline_json));

The above line is in document.ready

To get timeline_json, I've written a function. I'm pasting the code in the exact order of my code.

function get_json(){
  $.getJSON("https://script.google.com/macros/s/FILE_ID/exec", function(data) {
  console.log(data);  
  return data;
 });
}

 var timeline_json=get_json();
 console.log(timeline_json)


 window.timeline = new VCO.Timeline('timeline-embed', new VCO.TimelineConfig(timeline_json));

In the console, I'm getting object in this order

undefined
timeline.js:2950 Uncaught Invalid 
index.html:78 Object {title: Object, events: Array[18]}

If I get the object first, then it will work.


Solution

  • An ajax request is async by default (and should always be). You cannot return any value from an ajax request callback. What you can do is returning the promise (ajax request) from your method and then use relevant deferred method, e.g done():

    function get_json() {
        return $.getJSON("https://script.google.com/macros/s/FILE_ID/exec");
    }
    
    get_json().done(function (data) {
        window.timeline = new VCO.Timeline('timeline-embed', new VCO.TimelineConfig(data));
    });