ajax give me same data when call too frequently - javascript

I have a bar code gun, when i scan a bar code it will run the below function, but when I scan 5-6 bar code too fast it will give duplicate data
Also I need async to be true, or else it would be slow
Is there a way to do fix that so i don't have 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 added
$("#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 });
}
but I still get duplicated data

I had the same issue than you before. The solution that I got was passing in a numeric timestamp as a parameter when calling the php program, or passing in a date as parameter. Something like, for example:
xxxx.php?date=2014-03-28 20:54:52:03
It worked for me, I hope it works for you too...

This happens may because the web browser cached the data you request,by avoiding this you can try these:
use POST instead of GET in your request. assign POST to type in the parameters of $.ajax method.
disable cache. assign false to cache in the parameters of $.ajax method.
append an additional parameter and value to the url,a random number or a timestamp,like this xxxx.php?t=Math.random() or xxxx.php?t=new Date(). these make sure your request urls are different, and the response data will not be cached.

just like #user3311636 suggested, you can add an extra parameter on your Ajax calling code. So the server or your browser would not cache the response.
Try it like this (it is #user3311636 answer, i just include whole function for clarity purpose)
$.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 });

Related

jQuery -- nesting ajax calls and using data from each call - wikipedia API

I am having problems in nesting ajax calls with jQuery to wikipedia api.
The HTML is simple, just an input form and a button:
<input id='search-input' type="text" class="form-control">
<button id="search-button" type="button" class="btn btn-primary">Search</button>
<div id ='outputDiv'></div>
THe search button has an event listener that fires a function that grabs data from wikipedia API:
...
searchBtn.addEventListener('click', searchwiki);
...
function searchwiki(){
let searchTermObjects =[]
let term = inputfield.value;
let titleUrl = search_term(term);
createWikiObject(titleUrl).then(function(){
searchTermObjects.forEach(function(elem){
addExtrctToObj(elem)
})
}).then(function(data){
append_result(searchTermObjects)
})
}
function createWikiObject(titleUrl){
return $.ajax({
type: "GET",
url: titleUrl,
dataType : 'jsonp',
async: true,
error : function(ermsg){
console.log('error in searching',ermsg)
},}).then(function(data){
for(let i = 0; i < data[1].length; i ++){
searchTermObjects.push({
'title': data[1][i].replace(/\s+/g, '_'),
'description': data[2][i],
'url': data[3][i],
})
}; // this for loop should push each result as an object to an array named searchtTermObjects, and i am planning to use this array in the next ajax call to add another property named extract to each object in array
}
);
}
function addExtrctToObj(obj){
console.log(obj)
return $.ajax({
type: "GET",
url: get_text(obj['title']),
dataType : 'jsonp',
async: true,
error : function(ermsg){
console.log('error getting text',ermsg)
}
}).then(function (data){
let pageID = Object.keys(data.query.pages);
if(data.query.pages[pageID].hasOwnProperty('extract')){
obj['extract'] = data.query.pages[pageID].extract;
}
// this function adds the extracted text for each article ,
// the searchTermObjects now looks something like:
/ [{'title':...,'url':...,'description':...,'extract':..},{...}]
})
};
function append_result(termsObjectsArray){
// this function should loop through the searchtermobjects and append leading text for each object in the array to the Output div under the button
for (let i = 0; i < termsObjectsArray.length; i++){
let newDiv = document.createElement('div');
HOWEVER, Object.keys(termsObjectsArray[i]) returns only three keys at this time, and doesn't see the extract key'
console.log(Object.keys(termsObjectsArray[i]))
newDiv.classList.add('wiki-result');
newDiv.innerHTML = termsObjectsArray[i]["extract"];
HERE is where i get error -- the inerHtml of newDiv has value UNDEFINED
outputDiv.appendChild(newDiv);
}
}
// the api calls are formed with these functions:
let base_url = "https://en.wikipedia.org/w/api.php";
function search_term(term) {
let request_url = base_url + "?action=opensearch&search=" + term + "&format=json&callback=?";
return request_url;
}
function get_text(term){
let request_url = base_url + "?action=query&prop=extracts&exintro=&format=json&titles=" + term; // explaintex= returns plaintext, if ommited returns html
return request_url;
}
afetr I console.log(searchTermObjects) i get what i need, the array with objects that have all 4 properties with correct names, but I don't understand why the append_result function doesn't see the 'extract' key.
Next to the logged object in the console is the 'i' sign that says 'Value below was evaluated just now' , and there I have what I wanted -- every search result as an object with title, url, description, and extract keys.
copy this code to your IDE to see if you can help me with finding solution.
I believe the issue you're having is that you're attempting to return a Deferred object, and there's nothing to return yet because of the deferral.
return $.ajax({
type: "GET",
url: get_text(obj['title']),
dataType : 'jsonp',
async: true,
error : function(ermsg){
console.log('error getting text',ermsg)
}
})
The async value is true, so the code is moving on before the request is finished, and you're getting a null value back.
Try setting async: false and see if you get a better response. As pointed out by Andrew Lohr in the comments, this is not a good way to solve the problem, it will only tell you if that is the problem.
If it is, then I would recommend not breaking the request up into multiple functions. You should just chain the AJAX calls, using the deferral approach. It would be structured like this:
$.ajax({ ... }).then(function(data){
// ... do something with the data ...
// Make your followup request.
$.ajax({ ... }).then(function(data) {
// ... finalize the response ...
});
});
Also consider using the context option in the ajax call to pass in a callback method that can be fired once the chain is complete.

Push/Add multiple JSON objects one by one to the API using ajax and for loop

I'm working on a code where I can push a JSON objects one by one inside an array going to the API using AJAX and for loop. The code here is just a rough sample of what I have been working on. I can't seem to make it work on in pushing the objects to the API JSON array
var lms_json = <?php echo json_encode($json_data); ?>;
var jobjects = JSON.parse(lms_json);
var data = jobjects[0];
for ( i = 0; i < jobjects.length; i++ ) {
var data = jobjects[i];
$.ajax({
type : 'POST',
url : url,
data : data,
dataType : 'json',
success : function() {
console.log(success);
},
error : function(error) {
console.log('Error')
}
})
}
You need to use JSON.stringify to serialize your JSON object. Also, specify the content-type to make the server expect JSON data. This might work:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
I think that your problem is that AJAX is asynchronous process so you can do the following to do it correctly:
var lms_json = <?php echo json_encode($json_data); ?>;
var jobjects = JSON.parse(lms_json);
var i=0;
function makeAjax(url, objs){
var data = objs[i];
i++;
$.ajax({
type : 'POST',
url : url,
data : data,
dataType : 'json',
success : function() {
console.log(success);
makeAjax();
},
error : function(error) {
console.log('Error')
}
})
}
makeAjax(url,jobjects);
So After every success callback run it will run the next. so it will be synchronous process.
I hope it helps.

Returning php associative array from function to ajax call with json_encode() not and object

This is my first post so i apologize if i leave something out or don't explain myself very well. All this code is in the same php file
My ajax call
$.ajax(
{
type: "POST",
url: window.location.href,
data: {func: 'genString'},
datatype: 'json'
})
.done(function ( response )
{
console.log( response );
console.log( repose.string );
});
Which falls into an if statement on the page
if ( isset ($_POST['func'] && $_POST['func'] == 'genString')
{
exit(json_encode(myFunction()));
}
The function run on the page
function myFunction()
{
/* Would generate a string based on the database */
$arr = array('rows' => 1, 'string' => 'My test string');
// Changes values in the array depending on the database
return $arr;
}
This function is run to generate the array when the page itself is loaded and use the string portion to display the it and the rows part to set the height of a text area in the browser however when the ajax is called
console.log(respose) this logs
{"rows":1,"string":"My test string"} instead of an object
However when i try logging or using the string
console.log( response.string );
it shows up as undefined
I have done this previously and it has worked and returned an object which i can use in js with response.string. I have tried to use JSON_FORCE_OBJECT this had no effect on the result
Right now, the response is just being treated as a string (datatype). That's why response.string isn't working.
You can just tell by adding this:
console.log( typeof response );
So don't forget to put:
header('Content-Type: application/json');
Inside you if block:
And you have a typo on the if block (isset and response):
if ( isset ($_POST['func']) && $_POST['func'] === 'genString' ) {
header('Content-Type: application/json');
exit(json_encode(myFunction()));
}
On the JS typo also:
console.log( response.string );
^^
Well, it is a grammatical errors.
The request option
datatype: 'json'
should be
dataType: 'json'

Sequential ajax queries with jquery

I've spent quite a while trying to figure this out with various iterations of code, but with no luck. Coming from a php background I am new to javascript.
assume an array of three patches: patch1, patch2, patch3.
What I'm trying to achieve is:
an ajax call to the same php script for each patch, but each call must be made only after the previous call is completed
After all 3 are complete an ajax call to a separate php script is made.
Point 2 is working fine, point 1 not so.
Below is my code: the myAjaxInitialData func (and the underlying php script) is being called simultaneously for all 3 patches, rather than waiting for each to complete. The myAjaxGetSRCount is, correctly, not being called unitl all the patches are complete.
<body onload="initialData(0)">
<script>
function initialData(i) {
var patches = [<?php echo $jsPatchArray ?>];
var x = patches.length - 1;
var divId = "#initialData-patch-" +i;
var script = "ajax_initial_data.php";
var dataVar = "patch";
var data = patches[i];
if ( i != x) {
i++;
$.when(myAjaxInitialData(divId,script,dataVar,data)).then(initialData(i));
} else {
$.when(myAjaxInitialData(divId,script,dataVar,data)).then(myAjaxGetSRCount);
}
}
function myAjaxInitialData(divId,script,dataVar,data ) {
return $.ajax({
type: "GET",
url: script,
data: {patch:data},
success: function( response ) {
$( divId ).html( response );
}
});
}
function myAjaxGetSRCount() {
document.getElementById('srCount').innerHTML="Retrieving SR Counts..";
$.ajax({
type: "GET",
url: "ajax_sr_count.php",
success: function( response ) {
$( "#srCount" ).html( response );
}
});
}
</script>
Your problem seems to be here:
$.when(myAjaxInitialData(divId,script,dataVar,data)).then(initialData(i));
then takes a callback, i.e. a function. initialData(i) doesn't return anything so you are passing undefined into this function. If you mean to call initialData after this ajax request then you need to wrap it in a parameter-less function.
$.when(myAjaxInitialData(divId,script,dataVar,data)).then(function() { initialData(i); });
You should also be very aware that the value of i will be the value at the time of the callback. When closing over iterator variables, you should capture the value you expect before you create the callback. I.e.
if (i != x) {
i++;
var j = i;
$.when(myAjaxInitialData(divId,script,dataVar,data)).then(function() { initialData(j); });
}

Combining then sorting 2 feeds

I have the following script which works fine:
url = 'http://external_source/feed_1.xml';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
values = data.responseData.feed.entries;
if (values[0]) {
for (i = 0; i <= values.length - 1; i++) {
document.write(values[i].title);
document.write(values[i].publishedDate);
}
}
}
});
I now have a second feed, i.e. url = 'http://external_source/feed_2.xml';, and I need to combine both feeds. I understand i can repeat the above process and have feed_1 display above feed_2, but I need to combine both feeds and sort the feed entries by publishedDate.
How would I go about doing that? Both feeds are structured exactly the same, they just have different values in title and publishedDate
Since you're using jQuery you can use jQuery.when. The example at the bottom of that page shows you how to callback after multiple async methods are finished.
Since you'll have both data returned, you can just concat the arrays and sort them thereafter:
$.when( $.ajax( "/page1.json" ), $.ajax( "/page2.json" ) ).done(function( a1, a2 ) {
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
// Each argument is an array with the following structure: [ data, statusText, jqXHR ]
var data = a1[0].responseData.feed.entries.concat(a2[0].responseData.feed.entries)
});

Categories