Insert new record in MySQL via AJAX function

Viewed 17

I'm trying to count number of plays of an audio file by inserting a record in a MySQL table using AJAX every time the audio is played. Below is what I have done so far.

Audio

<audio id="audiotrack" preload="auto" type="audio/mp3" controls width="100%" onplay="addPlays()">
    <source src="tracks/<?Php echo $trkFile; ?>">
    Your browser does not support the audio tag.
</audio>

AJAX

<script type="text/javascript">
  function addPlays() {
      var trkId = <?php echo $trkid; ?>;
      $.ajax({
        type: "POST",
        url: "update-plays.php",
        data: trkId,
        cache: false,
        success: function() {
            alert('success');
        },
        error: function() {
            alert('error');
        }
      });
   }
</script>

PHP

$curdate = date('Y-m-d');
    
$trkid = isset($_POST['trkId']) ? $_POST['trkId'] : null;
$trkid = filter_var($trkid, FILTER_SANITIZE_NUMBER_INT);

$stmt = $connGWM->prepare("INSERT INTO tracklikes (tracklike, tracklikedate) VALUES (?, ?)");
$stmt->bind_param('is', $trkid, $curdate);
$stmt->execute();
$stmt->close();

For some reason i can't seem to understand, the record is not inserting into the table. Like the AJAX request is not working cause i don't get the alert if it was successful or not. What am I doing wrong? Any help is much appreciated.

1 Answers

probably you have same audio tags with the same id, use track id in the audio tag, and add it as a parameter to the function addPlays, this way when you click on it , it will pass the id to the ajax/php no matter how many tags you have

<audio id="<?php echo $track_id;?>" preload="auto" type="audio/mp3" controls width="100%" onplay="addPlays(this.id)">
    <source src="tracks/<?Php echo $trkFile; ?>">
    Your browser does not support the audio tag.
</audio>

<script type="text/javascript">
  function addPlays(track_id) {
      $.ajax({
        type: "POST",
        url: "update-plays.php",
        data: track_id,
        cache: false,
        success: function() {
            alert('success');
        },
        error: function() {
            alert('error');
        }
      });
   }
</script>
Related