Katherine Huang
Katherine Huang

Reputation: 68

How to force synchronous execution of getJSON?

For a school history project, I'm making a timeline webpage (live here). To avoid having to repeatedly type the details for each, I put them in a spreadsheet and exported it as JSON.

In the nav, I created links labelled with the year of the event using Javascript.

I want to then use slick.js, a jQuery plugin, to turn the nav into a carousel, as demonstrated an the /slick-test-static.html of the live website linked above.

My code:

$(document).ready(function(){
      $.getJSON("data.js", function(result){
        for (var i = 0; i < result.length; i++){
          var string = JSON.stringify(result[i]);
          var parsed = JSON.parse(string);

          $('.slider').append("<li><a href=\"#" + parsed.number + "\">" + parsed.year + "</a></li>");
        }
      });

      $('.slider').slick({
        slidesToShow: 8,
        slidesToScroll: 5,
        autoplay: true,
        autoplaySpeed: 3000
      });
    });

The links are created, but the slider isn't. I made a page where the links are created not using JSON, and it worked fine.

I think the problem is because the getJSON method is asynchronous, so the browser tries to create the slider before any items are even added to the slider. First, is this the problem? If so, what's the best way to fix it?

Upvotes: 1

Views: 1559

Answers (2)

Oleg
Oleg

Reputation: 692

Not sure if this helps for your concrete question, but you can indeed make synchronous JSON requests.

The asynchronous request would be (in vanilla JS):

var request = new XMLHttpRequest();
request.open("GET", "/bar/foo.txt", true); // Note the `true` here.
request.send(null);                       // When set to true, the request
                                         // will be asynchronous.
if (request.status === 200) {
  console.log("ok");
}

While the synchronous request would be:

var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
request.send(null);

if (request.status === 200) {
  console.log("ok");
}

You have some documentation here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

Upvotes: 0

micah
micah

Reputation: 8096

You can't make this synchronous. With ES6 you can "fake" waiting on asynchronous actions using async and await but what it's doing is essentially the same as what you need to do to make this work.

You need to stick your $('.slider').slick(... code inside of the $.getJSON callback. You should not initialize the slider until the async callback is made.

Upvotes: 1

Related Questions