ajax is providing identical data when called too frequently

Using my barcode scanner triggers the function below, but scanning multiple barcodes quickly results in duplicate data being processed.

The issue seems to be related to the async setting - when it's false, the process slows down significantly. Is there a solution to prevent receiving duplicate data?

function getUnReadBox() { 

$("#unReadBoxList").children().remove('li') ; 

$.ajax({ 
        dataType: "json",
        url: xxxx.php ,     
        success: saveUnRead , 
        error: function ( xhr , b , c ) { 
            $("#reportMsg").html ( "error" ) ;  },
        async: true }); 

}

function saveUnRead ( json ) { 

var i ; 
var new_item ; 
var msg ; 

for ( i in json ) { 
    new_item = '<li>' + json[i].PACKAGE_ID + "</li>" ; 
    $("#unReadBoxList").append ( new_item ) ; 
    scShipping.unReadBox ++ ; 

    $("#unReadBox").html ( msg ) ; 
}
$("#unReadBoxList").listview('refresh') ;
}

Edit

I made some additions:

$("#unReadBoxList").children().remove('li') ; 
 var d = new Date();
 var num = d.getTime();

var mySQL = scShipping.jsonUrl+'scTripUnRead.php?T='+scShipping.tripId+"&O="+scShipping.whichOp+"?date="+num ; 

$.ajax({ 
        dataType: "json",
        url: mySQL ,     
        success: saveUnRead , 
        error: function ( xhr , b , c ) { 
            $("#reportMsg").html ( "error" ) ;  },
        async: true }); 

}

Despite these changes, I'm still facing issues with duplicated data retrieval.

Answer №1

I faced a similar problem in the past like you did. The workaround I found was to include either a numerical timestamp or a date as a parameter when executing the php script. For instance:

xxxx.php?date=2014-03-28 20:54:52:03

This approach resolved the issue for me, hopefully it will do the same for you...

Answer №2

Perhaps this situation arises because the web browser has cached the data you requested. To prevent this from happening, you can try the following:

  1. Utilize POST instead of GET in your request. Set POST as the value for the type parameter in the $.ajax method.

  2. Turn off caching. Set false for the cache parameter in the $.ajax method.

  3. Add an extra parameter and value to the URL, such as a random number or timestamp, like xxxx.php?t=Math.random() or xxxx.php?t=new Date(). This ensures that your request URLs are unique, preventing the response data from being cached.

Answer №3

Following the advice of @user3311636, consider adding an additional parameter to your Ajax call code. This will prevent the server or browser from caching the response.

Here is an example implementation (credit goes to @user3311636, I have included the entire function for clarity):

$.ajax({ 
    dataType: "json",
    url: "xxxx.php?date=2014-03-28 20:54:52:03" ,     
    success: saveUnRead , 
    error: function ( xhr , b , c ) { 
        $("#reportMsg").html ( "error" ) ;  },
    async: true }); 

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

Error arises when using ODBC PDO alongside Ajax functionality

I've encountered a problem while working on a project at my job. I'm using PDO queries and ajax to generate dynamic elements, but I can't seem to fix a specific issue. The problem is that regardless of the option selected in two dynamically ...

Tips for extracting the image URL from my JSON string

I am in possession of a json file that includes URLs for images, and I have come across something that seems to be a URL, which is encoded as: iVBORw0KGgoAAAANSUhEUgAAADYAAAAzCAMAAADrVgtcAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6m ...

Having difficulty changing the visibility of a div element

I am currently working on a project that involves jQuery and ASP.Net. My main goal is to create a button that can hide/show a div using jQuery. Below is the code that I have implemented: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLI ...

Failure to append an object to the array occurs when submitting an HTML form

I am facing an issue with a form that is supposed to add input values to an array as objects when submitted. However, every time I submit the form, the console briefly shows that there is an array with one object, only for it to disappear. Below is the f ...

Switch your attention to the following input text using AngularJS

In my controller, I have an object variable called `myObject` with 3 input text fields in the user interface. I am looking for a way to automatically shift the focus to the next input field once the current one reaches its maximum length. var myObject = ...

How to choose the option in one select box based on the selection in another, and vice versa

How can I dynamically select options in one select box based on the selection of another, and vice versa? I am using Ajax to redirect to a query page. while($result = mysql_fetch_assoc($query1)) { echo "<option value=".$result['username' ...

Tips for retrieving the ajax results for multiple deferred calls using jQuery

I am struggling to utilize the jQuery deferred function as illustrated in the following code snippet. <script type="text/javascript"> var appUrls = { GetDataUrl : '@Url.Action("GetData")' }; ...

issue with selecting tabs in jquery

I need help with a problem that is connected to my previous article on CSS, button selection, and HTML tags. You can find the article here. I am not very proficient in JavaScript, so I would appreciate any insights or guidance on how to tackle this issue. ...

Iterate over the HTML elements within a class and retrieve a specific property in JSON

Currently, I am in the process of developing a straightforward application that involves making an Ajax request to retrieve a Json object and then passing it to an HTML document. Essentially, this application functions as a vending machine where the produc ...

Cross-Domain AJAX fails to include the X-Requested-With header in its requests

Set up a web service at http://www.a.com/service.asmx and then make a cross-domain ajax request to it from http://www.b.com. Take a look at the headers using Firebug, Live HTTP Headers, or another preferred plugin. When examining the request headers, you ...

JavaScript Tip: Effortless method to confirm the presence of duplicate values within an array

Similar Question: Best method for identifying duplicate values in a JavaScript array If I have an extensive array containing thousands of elements, I am looking to check if there are 2 or more elements with identical values and return true. I unders ...

Repeating items must be unique; duplicates are not permitted on ng-repeat

The data retrieved from the service request is in JSON format and looks like this: { "entries": [{ "id": 2081, "name": "BM", "niceName": "bodmas" }] }, { "id": 8029, "name": "Mas", "niceName" ...

Traverse through nested objects

I am currently working with JSON data containing information like uf, ivp, and others. My goal is to iterate over all the objects in order to access their properties. { "version": "1.5.0", "autor": "mindicador.cl", "fecha": "2018-10-31T13:00:00.000Z", "uf ...

During an AJAX call in MVC, the DDL remains unchanged

I am looking to update the value of location dynamically during an ajax call, in order to save the user time from manually changing it. I have attempted a solution but it doesn't seem to be working as expected. Any ideas on where I might be going wron ...

Storing persistent JSON data in a mobile app built with HTML5 involves utilizing the local storage capabilities of the

I am currently working on a mobile app using PhoneGap that is based on HTML technology. When the app is opened for the first time, my goal is to have it download a zip file that includes a JSON file and media files such as images or audio. Once the zip f ...

Issue with TableHead not functioning properly when sorting is requested

I'm currently facing an issue with my table that has clickable row headers for sorting functionality using the onRequestSort function. Unfortunately, it seems like this feature is not working as expected. I have implemented the sorting logic using rea ...

using async/await to retrieve data from a Google spreadsheet in Node.js

How can I use a for-loop to iterate through sheets in a Google spreadsheet and access specific cells within each sheet? I have a Google spreadsheet with Sheet1, Sheet2,... , Sheet5 where the cell values are Value1,..., Value5. The expected result should be ...

Has the Soundcloud web widget API become obsolete?

I am currently working with the SoundCloud widget API (). My main goal is to retrieve information about the tracks within a set. Unfortunately, it seems like I am only able to utilize the methods widget.getSounds() and widget.getCurrentSound successfully ...

Ensure that the line above is shorter in length compared to the following line

Is there a way to ensure that the previous line of text is always shorter than the next one, even if the length of the text is unknown? For example: Lorem ipsum dolor sit amet, consectetur adipiscing et libero posuere pellentesque. Vivamus quis nulla jus ...

Avoiding infinite loops in JavaScript events

This particular issue involves functions specific to D3, but is not limited to D3. I have developed two D3 charts and implemented zoom functionality on both with the intention of synchronizing the zoom scale and position - so that when one chart is zoomed, ...