AJAX - Alert with a beep sound each time a new entry is inserted into the database table

Having trouble determining the condition to test for when a new record is added to the database table. Can anyone lend a hand?

Here's a snippet of the data retrieved from the database:

['Paul Abioro', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9bebfaeef7fee3edb5b5b5dbfcf6faf2f7b5f8f4f6">[email protected]</a>', 'chester', 'Teejay', 'Hi Teejay', '3', '2023-04-06 17:42:54']
['Paul Abioro', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="314150445d5449471f1f1f71565c50585d1f525e5c">[email protected]</a>', 'chester', 'Teejay', 'How are you doing?', '3', '2023-04-06 17:42:58']

This is the AJAX code used to fetch records from the database, and I'm struggling with what to compare "datum.length" against in my conditional statement.

load_messages = function(){
     $.ajax({
         url:"json/chat-content.php",
         method:"POST",
         data:{recipient_id:query_id},
         dataType: "JSON",
         success:function(resp) {
          let datum = resp.response;
          //condition for when the new record is added to the database
           if(datum.length == ){
    
               let audio = new Audio("assets/audio/mixkit-confirmation-tone-2867.mp3");
               audio.play();

               

           }
            setTimeout(load_messages, 60000);
         },
         error: function (data) {
           console.log(data);
         }
     });

}

Answer №1

In my solution, I initialize a variable dataLength to 0. Then, using an if statement, I compare the value of this variable with the length of your data. If the condition is met, I update dataLength to match the new length of your data after the AJAX request has been completed.

let dataLength = 0;

load_messages = function(){
     $.ajax({
         url:"json/chat-content.php",
         method:"POST",
         data:{recipient_id:query_id},
         dataType: "JSON",
         success:function(resp) {
          let datum = resp.response;
          //checking if a new record has been added
           if(dataLength < datum.length){
    
               let audio = new Audio("assets/audio/mixkit-confirmation-tone-2867.mp3");
               audio.play();
           }
            dataLength = datum.length;
            setTimeout(load_messages, 60000);
         },
         error: function (data) {
           console.log(data);
         }
     });

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The hexagons configuration for tsParticles is experiencing technical difficulties

I'm struggling to implement the tsParticles library (specifically using react-tsparticles) in combination with the latest version of Next.js. However, when I try to use the particle.json file and bind it to the <Particles/> component, the partic ...

Building Secure Login Authentication with SimpleJWT in Django Rest Framework Using Templates and AJAX

When developing my application using Django Rest Framework and templates without a front-end application, I encountered an issue with authentication. I successfully created a login form and user list by referring to this documentation here. Everything work ...

Tips for updating the firebase access_token with the help of the next-auth credentials provider

Can anyone help me with refreshing the Firebase access token when it expires? I need the token for API authentication, but I can't find any information online regarding next-auth and Firebase. Currently, I am able to retrieve the access token but str ...

Encountering the error message "Unexpected token export" while attempting to implement the "framer-motion" package with Webpack

My experience with NextJS has been smooth sailing until now. I recently added the "framer-motion" module to animate some components, and it caused a major issue. Whenever I navigate to a page containing the import statement: import { motion } from "fr ...

What is the best way to create a general getter function in Typescript that supports multiple variations?

My goal is to create a method that acts as a getter, with the option of taking a parameter. This getter should allow access to an object of type T, and return either the entire object or a specific property of that object. The issue I am facing is definin ...

Seeking assistance for my dissertation assignment: electron, express, and SQLite3

I am currently dedicated to my thesis project, which involves designing an educational desktop video game for both public and private schools within my city. Being a fan of electron, I thought it would be a great idea to develop my app using this platform ...

Close any other panel when one is selected in a loop

I am experiencing difficulty with a series of menus that are causing other panels to hide when one is clicked and active. @{int i = 0;} @foreach (var levelOne in Model.MenuLevelOne) { <div class="panel-group" id="accordio ...

Wait until all information has been entered into the database before replying to the request

I have been exploring a way to insert multiple data in one call and only trigger a response after all the data has been inserted. Here is my current implementation: create: function(req, res) { var response = {}; var num = req.body.num; var re ...

I'm not skilled in programming, so I'm not sure what the problem is with the code

While working on my Blogger blog, I encountered the need to add a fixed sidebar ad widget that would float along the screen. After trying multiple codes, I finally found one that worked. However, using the template's built-in variable functions led to ...

Creating interactive routes and pages using Next.js and Prisma, embracing dynamic functionality

I have product information cards stored in my database, and I successfully display them on the user's page. Now, I want to add a "More Details" button on each card that will link to a new page (/pages/card/[id]). However, I'm unsure how to retrie ...

How can I extract the value of the first element in a dropdown using Javascript?

Imagine there is a dropdown menu with an unspecified number of options: <select id="ddlDropDown"> <option value="text1">Some text</option> <option value="text2">Some text</option> <option value="text3">Some ...

Ordering Algorithm in AJAX Grid

I have a specific requirement that I spotted on this website: Whenever a user clicks on the table header, the content should be sorted accordingly. I have successfully implemented this feature for tables with pre-set values. However, in my current scenar ...

Choosing bookmarkable views in Angular 5 without using routes

I'm currently working on a unique Angular 5 application that deviates from the standard use of routes. Instead, we have our own custom menu structure for selecting views. However, we still want to be able to provide bookmarkable URLs that open specifi ...

The transition from Vuetify3's VSimpleTable to VTable is ineffective and unsuccessful

The v-simple-table component has been renamed to v-table Old code that was using v-simple-table may not work correctly after the renaming. It is recommended to use v-data-table with the same data, as it works correctly. Here's the full page code: Yo ...

Display some text after a delay of 3 seconds using setTimeOut function in ReactJS

When using React JS, I encountered an issue where I am able to display text in the console after 2 seconds, but it is not appearing in the DOM. const items = document.getElementById("items"); const errorDisplay = () => { setTimeout(function () { item ...

Positioning tooltip arrows in Highcharts

I'm attempting to modify the Highcharts tooltip for a stacked column chart in order to have the arrow on the tooltip point to the center of the bar. I understand that I can utilize the positioner callback to adjust the tooltip's position, but it ...

Identify the currently active subitem within the item-active class in a PHP carousel slider

I am working on creating an image carousel slider with 4 items and 4 slides each. These images will act as radio buttons, and I want to highlight the slide corresponding to the selected radio button. So, when the carousel loads, the selected slide should b ...

The React Material UI Autocomplete, when combined with React-window, causes the list to re-render at the top

Looking for some assistance with React since I'm new to it. Having trouble with the Material-ui autocomplete component and need help from experienced React developers. The issue I'm facing is that when I choose an option from the autocomplete dr ...

Ways to invoke foo specifically when either a click event or a focus event is triggered

In my custom directive, I am binding focus and click events to an element: app.directive('mydirective', function () { return { link: function ($scope, $element, $attrs) { $element.bind('click focus', function (e) { f ...

What steps should I take to resolve a plugin error specifically related to index.js while using Cypress?

I am encountering an error in Cypress A plugin has thrown the following error, causing our tests to stop running due to a plugin crash. Please verify your plugins file (/home/dev2/Desktop/kavitaSeffcon/CypressProject/cypress/plugins/index.js) Error: ENOE ...