Skip to content
Advertisement

How can I make sure ajax/jquery calls finish before an html page loads?

$(function() {
    var $items = $('#items');
    $.ajax({
      type: "GET",
      url: 'some-url',
      data: {},
      success: function(items) {
        $.each(items, function(i, item){
          item_polys.push(item.polygon);
          $items.append(`<a href="somepage.html" onclick="localStorage.setItem('item', '${item.item_id}'); localStorage.setItem('item_poly', '${item.polygon}')";>${item.item_id}</a>`);
        });
        localStorage.setItem('item_polys', JSON.stringify(item_polys));
      },
      // Error handling 
      error: function (error) {
          console.log(`Error ${error}`);
      },
});

I need ‘item_polys’ to be saved into local storage before my corresponding html page loads. I would also settle for a way to reload the html page just one time each time after it loads, so that it will populate correctly. Thanks (and sorry if this has been answered already, I couldn’t quite find what I was looking for when I searched)

Advertisement

Answer

Since you want the ajax request to occur when the user is on the exact same page that the populated elements will be in, I think the only good way of doing this would be to create or display the elements of the page dynamically. (This might be as simple as toggling a display: none on and off, but it depends on what the page is like and what you want.)

So, make a function like populatePage that shows the page, where the default state of the page is a loading screen (or blank, or whatever you want the user to see when the request is in progress). Maybe something like

const populatePage = () => {
  const items = JSON.parse(localStorage.items);
  for (const item of items) {
    $items.append(`<a href="somepage.html" onclick="localStorage.setItem('item', '${item.item_id}'); localStorage.setItem('item_poly', '${item.polygon}')";>${item.item_id}</a>`);
  }
  $('main').show();
};

where main is the container you want to show when things are ready, and that has styling that hides it by default. Then:

On pageload, check if the item exists in storage. If so, use it, and call populatePage immediately. Otherwise, have the page keep showing the loading banner or blank screen, make the ajax request, and call populatePage when it’s finished.

$.ajax({
  // ...
  success: function (items) {
    localStorage.items = JSON.stringify(items);
    populatePage();
Advertisement