Search code examples
phpjqueryajaxsteamsteam-web-api

PHP, jQuery (AJAX) - Refresh Information


Refresh information, only when it's new, not always.

Updating data just when differs from response.

<script>
  $(document).ready(function(){
    setInterval(function() {
      $.ajax({
        type : "POST",
        url : "steam.php",
        cache : false,
        success : function(response) {
          var parsedResponse = $.parseJSON(response);
          $("#Display, [class='card-title display']").html(parsedResponse.display, parsedResponse.display);
          $("#AvatarFull, #AvatarSmall").attr("src", parsedResponse.avatar, parsedResponse.savatar);
          $("#Steam").attr("value", parsedResponse.display);
        }
      });
    }, 1000)
  });
</script>

Solution

  • You could achieve this by storing the response in a variable then comparing the new response. If they are the same, don't perform any action.

    Also note that html() and attr() only accept one and two arguments respectively, so the last one in each call can be removed. In any case it's preferred practice to use prop() over attr(). In addition use val(), not attr() to update the value of a control. Try this:

    $(document).ready(function() {
      let lastResponse;
    
      setInterval(function() {
        $.ajax({
          type: "POST",
          url: "steam.php",
          cache: false,
          success: function(response) {
            if (response != lastResponse) {
              var parsedResponse = $.parseJSON(response);
              $("#Display, [class='card-title display']").html(parsedResponse.display);
              $("#AvatarFull, #AvatarSmall").prop("src", parsedResponse.avatar);
              $("#Steam").val(parsedResponse.display);
              lastResponse = response;
            }
          }
        });
      }, 1000)
    });

    With all that being said I'd strongly suggest you use the observer pattern for this instead of AJAX polling. This is because it puts far less strain on the server resources and you can configure it to only send updates when new information is available. If you want to know more about this research Websockets and SignalR.