0

I'm trying to make a notification system that gets data every 5 secs but I don't know why it doesn't work properly. It outputs the notification endlessly but it should get the data and compare it to the last data it stored and if the data is not the same it should append the notification(s) and when it's the same it should alert "same".

  var appliedData;
  setInterval(getNotifications, 5000);
    function getNotifications(){
        $.ajax({
          type: 'GET',
          url: 'includes/socialplatform/friendsys/notifications.inc.php',
          dataType: "json",
          async: false,
          success: function(data) {
            if ( appliedData != data ) {
              appliedData = data;
              for(i=0; i < data.length; i++){
                $( ".notification-container" ).append('<div class="notification"><p>' + data[i].user +                    '</p></div>');
              }
            }else{
              alert("sammee");
            }
          }
        });
      }
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
  • It looks like your data is an array. You can't just compare arrays with `==` an `!=`. For example: `[1] == [1]` is `false`. The equality operators test for whether they are the same *object* not the same *value* You need to do a little more work to make a deep comparison. See: https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript – Mark Apr 15 '18 at 19:05

1 Answers1

1

Objects (any non-primitive: an array is an object) will never be equal to each other unless they reference the same place in memory. When comparing, your appliedData will always be different from your data, so that condition will always fail. If the response strings can be guaranteed to be the same when they represent the same object, you can simply compare the strings, as shown below. If not, you'll have to carry out a deep comparison instead.

let lastDataStr;
setInterval(getNotifications, 5000);
function getNotifications() {
  $.ajax({
    type: 'GET',
    url: 'includes/socialplatform/friendsys/notifications.inc.php',
    dataType: "text", // change here, then parse into an object in success function
    async: false,
    success: function(newDataStr) {
      if (newDataStr === lastDataStr) {
        alert('same');
        return;
      }
      lastDataStr = newDataStr;
      const newData = JSON.parse(newDataStr);
      newData.forEach(({ user }) => {
        $(".notification-container").append('<div class="notification"><p>' + user + '</p></div>');
      })
    }
  });
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • 1
    Maybe worth noting that since each item in `newData` is an object, the order of properties in each object is not guaranteed - so it's possible to get different strings for the same objects. – Mark Apr 15 '18 at 19:19