0

I have a website that reads from a MySQL database and displays the most recent data on a map. How can I make this data refresh on the website once a second? Do I need to put my AJAX code in a timer? Does the PHP script that queries the database need to be on a timer?

var geojson;
$(document).ready(function () {
  var a = $(this).val();
  console.log(a)
  $.ajax({
    type: "POST",
    url: "b.php",
    async: false,
    data: {c: a},
    datatype: 'json',
    success: function (d) {
      var e = JSON.parse(d);
      geojson = e;
      new L.GeoJSON(e);
      L.geoJSON([e], {
        onEachFeature: onEachFeature,

        pointToLayer: function (feature, latlng) {
          return L.circleMarker(latlng, {
            fillColor: "#ff0505",
            fillOpacity: 1,
            radius: 5,
            weight: 1
          });
        }
      }).addTo(mymap);
    }
  })
});
Adrien Brunelat
  • 4,492
  • 4
  • 29
  • 42
javanewbie14
  • 13
  • 1
  • 5

2 Answers2

0

I would recommend removing the async:false option, since using synchronous AJAX calls is not a good practice.

Then you can keep track of the time before performing a request, and upon completion, and calculate the timeout accordingly:

var func = function(){
    var interval=5000;
    var start = new Date();
    $.ajax({})
   .always(function(){
       var end = new Date();
       var timeout = interval - (end-start) 
       var timeout = timeout < 0 ? 0 : timeout;
       setTimeout(func, timeout);
   });
};
func();

You can alternatively utilise _.throttle from lodash.

var func = _.throttle(function(){
   $.ajax({....})
   .always(function(){
      func(); 
   });
}, 5000);

func();

In both of the above cases, a request will be performed every 5 seconds, or upon request completion (in case it lasts more than 5).

danwellman
  • 9,068
  • 8
  • 60
  • 88
Marinos An
  • 9,481
  • 6
  • 63
  • 96
  • That worked. It is getting the new values as they come in. However, it is no longer plotting the point. Console not showing any errors. hmmm – javanewbie14 Apr 11 '18 at 16:28
-1

You can compare data of latest dataresult and use with

setTimeout(function(){  
    yourfunction_name() 
}, 1000);
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Parasp2008
  • 21
  • 3