Stop inserting repeatedly if there is no new data available

I'm looking for a simple way to implement an if-else statement in my AJAX code to display new data only once it's found, without repeating the same data. Also, I need to figure out how to store the last ID as a variable so that I can use it when searching for more records.

Someone suggested that I could save the new notification idea as a return value so that it can be used by AJAX to retrieve the next set of results.

Does anyone have any suggestions on how to accomplish this?

<script type="text/javascript">
setInterval(function(){

var time = new Date().getTime();
  var notification_id="<?php echo $notification_id['notification_id'] ;?>"

$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&time="+time ,   
dataType:"json",
cache: false,
success: function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div  id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text"><a href="'+response['notification_id']+'">'+response['notification_content']+' </a><br />'+response['notification_time']+'</div></nr>');

 $("#mes").html(''+ response.num + '');
}
}
});
},20000);

</script>

Answer №1

In order to store the last id, you can utilize the following method:

window.localStorage.setItem('key', 'value');

When you need to retrieve it again, you would use:

var lastId = window.localStorage.getItem ('key'); 

To address the issue of duplicates, it is recommended to have an internal storage system to manage the incoming data. Using an array as a storage container is a feasible option, and you could even store this array in local storage.

Once you have set up your data storage mechanism, you can implement a check like the following to ensure that there are no duplicate entries:

var dataHandler = function (response){
   var isDuplicate = false, storedData = window.localStorage.getItem ('key');

   for (var i = 0; i < storedData.length; i++) {
     if(storedData[i].indexOf(response) > -1){
        isDuplicate = true;
     }
   }
   if(!isDuplicate){
     storedData.push(response);
   }
}; 

var printer = function(response){
   if(response.num){
      $("#notif_actual_text-"+notification_id).prepend('<div  id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text"><a href="'+response['notification_id']+'">'+response['notification_content']+' </a><br />'+response['notification_time']+'</div></nr>');

      $("#mes").html(''+ response.num + '');
    }
};

UPDATE

var notification_id = window.localStorage.getItem ('lastId'); 
    $.ajax({
    type: "GET",
    url: "viewajax.php?notification_id="+notification_id+"&time="+time ,   
    dataType:"json",
    cache: false,
    success: function(response){
    if(response){
    dataHandler(response);
    if(response.num){
       window.localStorage.setItem('lastId', response.num);
    }
    });
    },20000);

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

How come defining the state using setTimeout does not display the accurate properties of a child component?

Presented here is a component designed to render a list of items and include an input for filtering. If no items are present or if the items are still loading, a message should be displayed. import { useState } from "react"; export const List = ...

NPM is currently malfunctioning and displaying the following error message: npm ERR! 404

When running npm update -g, the following error occurs: npm ERR! code E404 npm ERR! 404 Not found : default-html-example npm ERR! 404 npm ERR! 404 'default-html-example' is not in the npm registry. npm ERR! 404 You should bug the author to publi ...

Implementing a JQuery function to generate a popup whenever a user clicks on a table row (tr) in an

I am working on a JSP page that contains a table, and I want to implement a pop-up window functionality when clicking on a specific row in the table. I have attempted to use JavaScript to connect with the row but so far, I have not been successful in creat ...

What are the ways in which Angular can offer assistance to Internet Explorer 9?

The news is out - the Angular team has just announced their support for Internet Explorer 9! This revelation has left me wondering, how is it even possible? Currently, I am an avid user of AngularJS and have dedicated time to studying its ins and outs. Fr ...

Show a loading animation during an ajax request for a post

Despite the vast number of examples available online, I am looking for a way to incorporate a loading GIF image into my existing script while data is being retrieved. My java skills are lacking, so I need assistance with modifying the following code: < ...

"Utilizing a Handlebars Helper to Evaluate if Two Values (v1 and v2) are Equal, and Displaying Content from

To make the actual call, I require something along these lines: <script id="messagesTemplate" type="text/x-handlebars-template"> {{#each messages.messages}} {{#each to}} {{#ifCond username messages.sessionUserName}} <h1> ...

Is there a way for me to adjust the image dimensions so that it doesn't surpass the width of its parent container?

When working with images, it can be tricky to set the original width while also ensuring it fits within a parent container. For example, if the parent container has a width of 1000px, you may want the image to have a max-width of 100%, but not exceed 1000p ...

TypeScript does not perform type checking on arrays created using the Array() constructor and filled with the fill method

Using TypeScript version 2.4.2, compiled with the --target ES6 option has interesting results. For example, when using this line of code: var coins: { coin: number}[] = [1,1,1] TypeScript throws an error: Error TS2322: Type 'number[]' is no ...

Issue with ERR_HTTP_HEADERS_SENT persists despite implementation of return statements

When attempting to send a POST request to the server, an error is encountered: Error [ERR_HTTP_HEADERS_SENT]: Cannot modify headers after they are sent to the client at new NodeError (node:internal/errors:371:5) at ServerResponse.setHeader (node:_h ...

Exploring the Power of Elasticsearch with Datatables

I'm attempting to utilize functions from an Elasticsearch instance in conjunction with datatables to exhibit results. Currently, I am only able to display 10 results, regardless of the query used. Even though there are 141,000 results in Elasticsearc ...

What is the method used by three.js to render video with spherical UV mapping?

I have a streaming video displayed in a 3*3 format. I am able to splice the entire video into individual sections using THREE, // Creating a 3x3 PlaneGeometry var geometry = new THREE.PlaneGeometry(400, 200, 3, 3); const video1 = document.getElem ...

Select the top row of a table when the checkbox is ticked to emphasize it

Previously, I tackled a challenge on a webpage using jQuery where checkboxes in a table needed to be selected based on specific data attributes. Essentially, if one checkbox in a row was selected, the rest of the checkboxes would be disabled if their data ...

tips for accessing the useState value once it has been initialized

When using the state hook in my code, I have: const [features, setFeatures] = useState([]) const [medicalProblem, setMedicalProblem] = useState([]) The medicalProblem variable will be initially populated with a response from an API call: useEf ...

sending data to a Laravel Controller via Ajax results in receiving null data

My Ajax implementation is not working as expected. When I send data to the controller, it seems to be empty and nothing gets sent. However, if I try to retrieve the data using jQuery before sending it, I do get the correct data. Here is the Ajax code: $.a ...

Incorporate an onclick event to the elements within the array

I'm currently working on iterating over an array and adding an onclick event to each element. My goal is to be able to click on each div and have them log their values in the console. However, I am facing a challenge in applying the onclick event to e ...

The JSON data URLs in the `_next/data` directory of the NextJS app are returning a 404 error, however, when accessed directly in the

I am facing an issue with my Next.js (v13) app hosted on a self-hosted Kubernetes cluster. The AJAX JSON data calls from the _data directory are showing as 404 errors, even though when I directly visit the URLs in my browser, they load fine. I'm perp ...

Tips for handling promise coverage within functions during unit testing with Jest

How can I ensure coverage for the resolve and reject functions of a promise within a function while conducting unit tests using Jest? You can refer to the code snippet below. Service.js export const userLogin = data => { return AjaxService.post( ...

Best return type for a webservice triggered using jQuery but not requiring any data to be returned

I am currently working on a web service that utilizes several methods. These methods do not have significant impact on the client side as I call them using jQuery/ajax. My main concern is regarding the recommended return type. Typically, I would return JS ...

Oops! An issue has occurred where I am unable to access certain properties (specifically 'Symbol(__APOLLO_CONTEXT__)') while utilizing the Apollo provider

When attempting to implement a query in my upcoming app, I encountered an error that reads: Error: Cannot read properties of undefined (reading 'Symbol(APOLLO_CONTEXT)') This is the setup of my Apollo client: import { ApolloClient, InMemoryCache ...

How about wrapping a large amount of text three times and including a "read more" link?

I am tasked with creating an HTML element that automatically detects when text has wrapped three times, truncates the content, and adds a "more..." link at the end of the third line. Can this be achieved? If yes, what is the process to implement it? ...