Home > Software design >  Play audio if new data is added mysql
Play audio if new data is added mysql

Time:03-07

I have a snippet of code that sends a request to the server every 10 seconds and pulls out the information A sound is played when this happens,But I want the sound to play if a new row is added to the database Audio is now played each time reloadData is run

js code

<script>
     
    setInterval(function() {
        reloadData();
    }, 10000); 
    function reloadData(){
        $.ajax({
            url: "<?=baseUrl()?>/panel/players"
        }).done(function(data){
            $("#players").empty();
            $("#players").append(data);
            var audio = new Audio('Audio.mp3');
            audio.play();
        });
    }
    
    $(function() {
        reloadData();
    });
</script>

controller

public function players()
    {
        $data['players'] = SellModel::fetchPlayer();
        View::renderPartial('panel/players.php' , $data);
    }

Model

public static function fetchPlayer()
    {
        $db = Db::getInstance();
        $record = $db->query("SELECT * FROM h_player WHERE status=1");
        return $record;
    }

CodePudding user response:

To do what you require you can retrieve the number of elements which #players contains before the update and compare it to the number of elements it contains after the update. If they are different, then play the sound.

The below example assumes that the row elements are direct children of #players, but this can easily be amended if the HTML is not in this exact structure.

let firstLoad = true;

function reloadData() {
  let $players = $('#players');

  $.ajax({
    url: "<?=baseUrl()?>/panel/players"
  }).done(function(data) {
    var oldCount = $players.children().length;   
    $players.html(data);
    let newCount = $players.children().length;
    
    if (!firstLoad && oldCount < newCount) {
      var audio = new Audio('Audio.mp3');
      audio.play();
    }

    firstLoad = false;
  });
}

As an aside, note that AJAX polling is not good practice and should be avoided where possible as it does not scale. A better approach would be to use the observer pattern with something like Websockets to keep the UI and server side data in close synchronicity, however this will require re-writing your server side logic which handles the updating of player data.

  • Related