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)
});
Related
I'm trying to make a notification system that gets data every 5 secs but I don't know why it doesn't work properly. It outputs the notification endlessly but it should get the data and compare it to the last data it stored and if the data is not the same it should append the notification(s) and when it's the same it should alert "same".
var appliedData;
setInterval(getNotifications, 5000);
function getNotifications(){
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "json",
async: false,
success: function(data) {
if ( appliedData != data ) {
appliedData = data;
for(i=0; i < data.length; i++){
$( ".notification-container" ).append('<div class="notification"><p>' + data[i].user + '</p></div>');
}
}else{
alert("sammee");
}
}
});
}
Objects (any non-primitive: an array is an object) will never be equal to each other unless they reference the same place in memory. When comparing, your appliedData will always be different from your data, so that condition will always fail. If the response strings can be guaranteed to be the same when they represent the same object, you can simply compare the strings, as shown below. If not, you'll have to carry out a deep comparison instead.
let lastDataStr;
setInterval(getNotifications, 5000);
function getNotifications() {
$.ajax({
type: 'GET',
url: 'includes/socialplatform/friendsys/notifications.inc.php',
dataType: "text", // change here, then parse into an object in success function
async: false,
success: function(newDataStr) {
if (newDataStr === lastDataStr) {
alert('same');
return;
}
lastDataStr = newDataStr;
const newData = JSON.parse(newDataStr);
newData.forEach(({ user }) => {
$(".notification-container").append('<div class="notification"><p>' + user + '</p></div>');
})
}
});
}
Challenge:
While on URL1(random wikipedia page), make an ajax request to URL2(100 most common words wikipedia page), format a list out of the returned data to be used later.
I have to run this from the console while on "URL1"
example:
Navigate to URL1
Open Console
paste code
hit enter
So far I have been able to grab the entire html source while on URL1 with the following:
$.ajax({
url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type: 'GET',
dataType: 'html',
success: function (response) {
console.log(response); // works as expected (returns all html)
}
});
I can see in the console the entire HTML source -- I then went to URL2 to figure out how to grab and format what I needed, which I was able to do with:
var array = $.map($('.wikitable tr'),function(val,i){
var obj = {};
obj[$(val).find('td:first').text()] = $(val).find('td:last').text();
return obj;
});
console.log(JSON.stringify(array));
Now this is where my issue is -- combining the two
$.ajax({
url:'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type:'GET',
dataType:'html',
success: function(data){
// returns correct table data from URL2 while on URL2 -- issue while running from URL1
var array = $.map($('.wikitable tr'),function(val,i){
var obj = {};
obj[$(val).find('td:first').text()] = $(val).find('td:last').text();
return obj;
});
console.log(JSON.stringify(array));
};
});
Im guessing this is due to the HTML I want to map is now a string, and my array is looking for HTML elements on the current page which it of course would not find.
Thanks
Simple fix here! You're exactly right, it's not parsing the html you return, so just tell jQuery to convert it into an object it can use $(data) and use that to find what you need.
In essence, your 'document' now becomes $(data) which you will use as the source of all your queries.
$.ajax({
url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type: 'GET',
dataType: 'html',
success: function(data) {
var myVar = data;
Names = $.map($(myVar).find('.wikitable tr'), function(el, index) {
return $(el).find('td:last').text()
});
console.log(Names);
}
});
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 });
I want to implement multiple ajax post requests. Suppose there are 3 posts. Then the 2nd post is dependent on the result from the first and the third post is dependedent on the result received from the 2nd post.
How do I place the 2nd ajax post method. Should it be done in the success handler
jQuery.ajax({
type : "post",
dataType : "json",
url : ajaxurl,
data : form_data,
async: false,
success: function(response) {
//2nd ajax post call to be placed here?
}
}
})
//or should 2nd ajax post call be placed after
I have seen some people also using jQuery.when() but I am not sure whether I could use that.
Since here I will have to check for when condition 3 times.
Thanks in Advance.
Something like this?
From https://api.jquery.com/jQuery.when/
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).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 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"
if ( /Whip It/.test( data ) ) {
alert( "We got what we came for!" );
}
});
a1, a2 being the results returned from the various callbacks?
(This will however execute your three callbacks (async), but return the results of all three)
Otherwise if you've got a dependency from request1 to request2 you can do something like this https://api.jquery.com/jQuery.ajax/
$.ajax("page1.php").done(function(a1) {
if (a1 == "something") { // if 2nd call dependent on results from 1st
$.ajax("page2.php").done(function(a2) {
}).fail(function() {
// handle with grace
});
}
}).fail(function() {
// handle with grace
});
I have a series of ajax calls that fill columns on a page.
var doneDefers = function(defer) {
// leftColDefer is another deferred that sets some header info
$.when(defer, leftColDefer).done(function(req1, req2){
var data = req1[0],
head = req2[0];
// spit this data out to elements on the page
});
};
for(i=0;i<window.ids.length;i++){
defer[i] = $.ajax({
url: 'api/get_runs_stats.php',
type: 'GET',
dataType: 'json',
data: {
run_id: window.ids[i]
}
});
doneDefers(defer[i]);
}
This works fine. If an ajax call fails, nothing is spit out and all is right with the world.
Now I want to do some calculations based on all the data that got spit out.
$.when.apply(null, defer)
.done(function() {
var args = Array.prototype.slice.call(arguments);
calcDeltas();
})
.fail(function() {
var args = Array.prototype.slice.call(arguments);
console.log('in list fail');
});
The done function works fine none of the ajax calls fail. If one of them fail, I go into the fail function and I don't have access to any of the return data from the other runs. The arguments array only has the failed call's data.
I would like to do my calculations on the data sets that passed. How can I get to the data from the good calls when one of them fails?
I'm not sure this is the simplest solution but it stands a chance of working.
var ajax_always_promises = [],//to be populated with promises that (barring uncaught error) are guaranteed to be resolved.
data_arr = [],//an array to be (sparsely) populated with asynchronously delivered json data.
error_arr = [];//an array to be (sparsely) populated with ajax error messages.
$.each(window.ids, function(i, id) {
var dfrd = $.Deferred();
var p = $.ajax({
url: 'api/get_runs_stats.php',
type: 'GET',
dataType: 'json',
data: {
run_id: window.ids[i]
}
}).done(function(json_data) {
data_arr[i] = json_data;//intentionally not `data_arr.push(json_data);`
}).fail(function(jqXHR, textStatus, errorThrown) {
error_arr[i] = textStatus;//intentionally not `error_arr.push(textStatus);`
}).always(dfrd.resolve);
ajax_always_promises[i] = dfrd.promise();
doneDefers(p);
});
$.when.apply(null, ajax_always_promises).done(function() {
//The data in the (sparsely) populated arrays `data_arr` and `error_arr` is available to be used.
var i, id, success_count=0, error_count=0;
for(i=0; i<Math.max(data_arr.length,error_arr.length); i++) {
//Here, the index i corresponds to the original index of window.ids ...
//...that's the advantage of sparsely populating the arrays.
id = window.ids[i];
if(data_arr[i]) {
//Here, do whatever is required with `data_arr[i]`, and `id` if needed.
success_count++;
}
else if(error_arr[i]) {
//Here, do whatever is required with `error_arr[i]`, and `id` if needed.
error_count++;
}
}
console.log("Success:errors: " + success_count + ':' + error_count);
});
Untested - may well need debugging