Search code examples
javascriptjqueryajaxgetoffline

How to queue ajax request in offline mode and execute automatically when connects to internet using offline .js ?


Please explain with one ajax example. This is my current code

<div id="status">Status is:</div>
  <button onclick="getData()">Get Data</button>
  <script>
      // Set our options for the Offline detection library
      Offline.options = {
          checkOnLoad: true,
          checks: {
              image: {
                  url: function() {
                      return 'http://esri.github.io/offline-editor-js/tiny-image.png?
                  }
              },
              active: 'image'
          },
          requests : true
      }

      Offline.on('up', internetUp);
      Offline.on('down',internetDown);
      var statusDiv = document.getElementById("status");
      statusDiv.innerHTML = "Status is: " + Offline.state;

      function getData() {

          // See if internet is up or down
          Offline.check();
                  // If the internet is up go ahead and retrieve data.
                  $.ajax({url:"http://rest-service.guides.spring.io/greeting", success: function(result){
                    debugger
alert(JSON.stringify(result));
    }});

      }

      function internetUp(){
          console.log("Internet is up.");
          statusDiv.innerHTML = "Status is: up";
      }

      function internetDown(){
          console.log("Internet is down.");
          statusDiv.innerHTML = "Status is: down";
      }
  </script>

I want to queue the ajax request calling in offline mode during calling and want to execute automaticaly when i connect to internet


Solution

  • Offline.on('up', internetUp); is an event that fire internetUp function when internet is up. Then you could do something like:

        function internetUp(){
                  console.log("Internet is up.");
                  statusDiv.innerHTML = "Status is: up";
    
                  var requests = ['example.com','example2.com','whatever.com'];
    
    
                  for(let i =0;i<requests.length;i++){
    
                                $.ajax({
                        url: requests[i]
                      }).done(function(data) {
                        console.log(data);//here callback of each request
                      });          
                  }
    }
    

    Where requests represents the queue ajax actions you want stored as array.