jquery AJAX pulls data from XML - last 4 items only - ajax

I am working on a sort of aggregator/tweet wall. At the mo it only uses data from an XML file (of our latest news). I made a bit of a mistake in the logic, though.
At present it only pulls items from the last 30 days. Live demo takes a few secs to load (using last 240 days for extra content to work with). However, I need it to:
Pull the last 4 items in chrono order.
Shuffle that array so they are
random ordered (but will all be "fresh" news).
Output that array.
jQuery(function () {
$.ajax({
url: 'http://www.sagittarius-digital.com/news.rss',
dataType: 'xml',
complete: function() {
/*Init masonry.js*/
var container = document.querySelector('#container');
var msnry = new Masonry( container, {
// options
gutter: 20,
columnWidth: 320,
itemSelector: '.item'
});
}
}).done(function (xml) {
var items = [];
$(xml).find('item').each(function () {
var $item = $(this);
var date = new Date($item.find('pubDate').text());
var date_30 = new Date().getTime() - (1000*60*60*24*240); /* last figure = number of days to sort back from */
var yyyymmdd = date.getFullYear() + '' + (date.getMonth() + 1) + '' + date.getDate();
if ( date_30 < date.getTime() ) { // newer than 30 days
var array = '<div class="item"><h2>News</h2>';
array += '<p>' + yyyymmdd + '</p>';
array += '<a href="' + $item.find('link').text() + '">';
array += '<h2>' + $item.find('title').text() + '</h2>';
array += '<p>' + $item.find('description').text() + '</p>';>
array += '<p>Category: ' + $item.find('category').text() + '</p>';
array += '</a>';
array += '</div>';
items.push(array);
}
});
$('div.item').after(items.join(' '));
}).fail(function () {
console.log('error', arguments)
});
});
Basically after that I need to add a second RSS feed with different info doing the same, a Twitter ajax call and facebook ajax call. So I will have 12 bits of data that are all the 4 "freshest", these will then shuffle into a random order and output, so there is a nice even mix.

Related

Count elements in ajax/json response

This is properly pretty simple and has been asked many times before, but it just eludes me, who to do it.
I have 2 dropdowns, where the last one gets populated from the select of the first one. That works, but now I want to preselect for the second dropdown, when there is only one element in the response.
Function:
$( "select[name='r53b']" ).change(function () {
var r53bID = $(this).val();
if(r53bID) {
$.ajax({
url: "/overfladeajax.php",
dataType: 'Json',
data: {'id':r53bID},
success: function(data) {
$('select[name="r53c"]').empty();
$('select[name="r53c"]').append('<option value="">Vælg Lagtykkelse</option>');
$.each(data, function(key, value) {
$('select[name="r53c"]').append('<option value="'+ key +'">'+ value +'</option>');
});
}
});
}
});
2 kind of reponses:
{"7":"2 x 100 \u03bcm HS 150 (totalt 200 \u03bcm t\u00f8rfilm)","8":"1 x 40 \u03bcm zink primer + 1 x 120 \u03bcm HS 150 (totalt 160 \u03bcm t\u00f8rfilm)"}
or
{"2":"1 x 80 \u03bcm HS 150"}
How to I make the append, so it will also select the option where only one is available?
You can use Object.keys(yourjson).length to get the length of keys in your json object and then if the count is 1 add selected to that options.
Demo Code :
var data = {
"2":"1 x 80 \u03bcm HS 150"
}
var count = Object.keys(data).length//get key length
console.log("length is "+count)
$('select[name="r53c"]').append('<option value="">Vælg Lagtykkelse</option>');
$.each(data, function(key, value) {
//if length is 1
if (count == 1) {
$('select[name="r53c"]').append('<option selected value="' + key + '">' + value + '</option>');
} else {
$('select[name="r53c"]').append('<option value="' + key + '">' + value + '</option>');
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="r53c">
</select>

How to parse the RSS using google api or any other techinques

I want to parse the below mentioned RSS in order to get the title, description, image and date. Currently i'm able to get the all other details except image. Im using google api feed to parse the rss. Please can anyone me in this context.
RSS:https://news.google.com/news/feeds?cf=all&ned=in&hl=en&q=cricket&output=rss
// Google Feed API: https://developers.google.com/feed/
// Inspiration: http://designshack.net/articles/javascript/build-an-automated-rss-feed-list-with-jquery/
function parseFeed(url, container) {
$.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=5&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function (data) {
// log object data in console
console.log(data.responseData.feed);
// append feed link and title in container
$(container).append('<span class="iconicstroke-rss-alt"></span>');
$(container).append('<h1 class="feed">' + data.responseData.feed.title + '</h1>');
// for each entry... *
$.each(data.responseData.feed.entries, function (key, value) {
// * create new date object and pass in entry date
var date = new Date(value.publishedDate);
// var thumbnail = entry.mediaGroups[0].contents[0].url;
// * create months array
var months = new Array(12);
months[0] = 'January';
months[1] = 'February';
months[2] = 'March';
months[3] = 'April';
months[4] = 'May';
months[5] = 'June';
months[6] = 'July';
months[7] = 'August';
months[8] = 'September';
months[9] = 'October';
months[10] = 'November';
months[11] = 'December';
// * parse month, day and year
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
// * assign entry variables
var title = '<h3 class="title">' + value.title + '</h3>';
var time = '<p class="time">' + months[month] + ' ' + day + ', ' + year + '</p>';
var snippet = '<p class="snippet">' + value.contentSnippet + '</p>';
var img = '<p class="snippet">' + value.thumbnail + '</p>';
var entry = '<div class="entry">' + title + time + snippet + '</div>';
// * append entire entry in container
$(container).append(entry);
});
},
// if there's an error... *
error: function (errorThrown) {
// * log error message in console
console.log(errorThrown);
// * show error message
alert('Houston, we have a problem.');
}
});
}
$(document).ready(function () {
parseFeed('https://news.google.com/news/feeds?pz=1&cf=all&ned=en&hl=in&q=aishwarya%20rai&output=rss', '#csstricks');
});
Just add this to your script
var content = document.createElement("content");
content.innerHTML = value.content;
var images = "";
$(content).find('img').each(function() {
images += this.outerHTML;
});
var img = '<p class="snippet">' + images + '</p>';
Same answer as here: https://stackoverflow.com/a/26369373/989257
Codepen example: http://codepen.io/janih/pen/JdPMZX

Google Map doesn't appear on load

I am developing an app where I use 2 API's a.k.a Instagram API and Google Map API. Using AJAX, I get the first set of Images filtered by a tag name. In the 1st set we receive 20 images. Among the received images, the images that have the latitude and longitude info (geotagged images) are displayed on the map.
Now the first time when my page loads, I cannot see the map. But when I press the load more button to get the next set of images, the Map works fine showing my previous images too.
Here is the code for what happens on page load:
$( window ).load(function() {
$.ajax({
type: "GET",
url: "https://api.instagram.com/v1/tags/nyc/media/recent?client_id=02e****",
dataType:'JSONP',
success: function(result) {
onAction(result, 2, tag);
instaMap(result, 2, from);
}
});
});
These are the functions being called:
/**
* [initialize description]
* Initialize the map with markers showing all photos that are geotagged.
*/
var initialize = function(markers) {
var bounds = new google.maps.LatLngBounds(),
mapOptions = {
scrollwheel: false,
mapTypeId: 'roadmap',
center: new google.maps.LatLng(22.50, 6.50),
minZoom: 2
},
gmarkers = [],
map,
positions,
markCluster;
markers = remDuplicate(markers);
// Info Window Content
var infoWindowContent = [];
for (var j = 0; j < markers.length; j++ ) {
var content = [
'<div class="info_content">' +
'<h3>' + markers[j][2] + '</h3>' +
'<a href="' + markers[j][3] + '" target="_blank">' +
'<img src="' + markers[j][4] + '" style="z-index:99999">' + '</a>' +
'</div>'
];
infoWindowContent.push(content);
}
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Display multiple markers on a map
var oms = new OverlappingMarkerSpiderfier(map);
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
positions = new google.maps.LatLng(markers[i][0], markers[i][1]);
marker = new google.maps.Marker({
position: positions,
map: map,
animation:google.maps.Animation.BOUNCE,
title: markers[i][2]
});
oms.addMarker(marker);
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.close();
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
map.setCenter(marker.getPosition());
};
})(marker, i));
gmarkers.push(marker);
}
google.maps.event.addListener(map, 'click', function() {
infoWindow.setMap(null);
});
markCluster = new MarkerClusterer(map, gmarkers);
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
map.setZoom(2);
google.maps.event.removeListener(boundsListener);
});
};
/**
* [onAction]
* OnAction() function helps in loading non-geotagged pics.
*
* #param {[type]} result [Result retruned from the Instagram API in json format]
* #param {[type]} likey [hearts the user has entered as per which the posts will be filtered]
*/
var onAction = function (result, likey, tag) {
$('.load-pics').remove();
if (result.pagination.next_url) {
paginate = removeURLParameter(result.pagination.next_url, 'count');
}
$.each(result, function(key, value) {
if (key === 'data') {
$.each(value, function(index, val) {
liked = val.likes.count;
link = val.link;
imgUrl = val.images.low_resolution.url;
locations = val.location;
if (liked >= likey) {
if (locations === null) {
output = '<li class="img-wrap">' + '<div class="main-img">' +
'<a href="' + link + '" target="_blank">' +
'<img src="' + imgUrl + '" ><span class="hover-lay"></span></a>' +'<p>' +
'<span class="heart"></span><span class="likes-no">' + liked + '</span>' +
'<span class="comment-box"></span><span class="comment-no">' +
val.comments.count + '</span> ' + '</p>' + '</div>' +
'<div class="img-bottom-part">'+ '' + '<div class="headin-hastag">' +
'by ' + '<h2>Sebastien Dekoninck</h2>#hello <span>#kanye</span> #helloagain #tagsgohere</div>'
+'</div></li>';
$('#instafeed').append(output);
}
}
});
}
});
if ($('#instafeed').children().length === 0) {
alert('There are no pics with ' + likey + ' likes or #' + tag + ' was not found.');
} else {
// $('.not-geo').remove();
// $('#instafeed').before('<button class="not-geo">Click To See Images That Are Not Geotagged <img src="assets/imgs/down.png" ></button>');
}
$('#instafeed').append('<div class="load-pics"><button id="show-more">Show more <span></span></button> </div>');
};
/**
* [instaMap]
* instaMap() will be the function which will deal with all map based functionalities.
*/
var instaMap = function(result, likey, from) {
$('.load-mark').remove();
if (result.pagination.next_url) {
pagiMap = removeURLParameter(result.pagination.next_url, 'count');
}
$.each(result, function(key, value) {
if (key === 'data') {
$.each(value, function(index, val) {
liked = val.likes.count;
link = val.link;
imgUrl = val.images.low_resolution.url;
locations = val.location;
if (liked >= likey) {
if (locations && locations.latitude !== null) {
tempArr = [
locations.latitude,
locations.longitude,
val.user.username,
val.link,
val.images.low_resolution.url
];
mark.push(tempArr);
}
}
});
}
});
if (mark.length) {
initialize(mark);
$('.map-parent-wrapper').append('<div class="load-mark"><button id="show-mark">See More </button></div>');
} else {
alert('No geotagged pics found in the retrieved set. Click see more');
$('.map-parent-wrapper').append('<div class="load-mark"><button id="show-mark">See More </button></div>');
}
};
I have created a See More button to retrieve the next set of images and load those on the Map. When clicking see more, everything seems to work fine. Not sure why it's happening so. Console.log does not show any error. Also, all the values I feed does flow appropriately. I even tried clearing cache. Not sure, why it's happening.
If instaMap is the function which is going to handle all your map based functionality, it has to be the one that loads map in your $( window ).load function ();
Otherwise, if you want Google maps to load on initial window load you need to put below in there:
google.maps.event.addDomListener(window, 'load', initialize);

Pass parameters in a Node.js GET Ajax

I would like to send an AJAX request to the router function below with parameters start and end respectively.
Those variables would influence the results I get back from the request.
router.get('/winnerlist', function(req, res) {
var db = req.db;
var start = "20140621";
var end = "20140623";
db.collection('userlist').find({"timestamp": {"$gte": start, "$lt": end}}).toArray(function (err, items) {
res.json(items);
});
});
This is my AJAX GET call
function populateWinners() {
// Empty content string
var tableContent = '';
// jQuery AJAX call for JSON
$.getJSON( '/users/winnerlist', function( data ) {
userListData = data;
console.log(data);
// For each item in our JSON, add a table row and cells to the content string
$.each(data, function(){
tableContent += '<tr>';
tableContent += '<td>' + this.id2+ '</td>';
tableContent += '<td>' + this.email + '</td>';
tableContent += '<td>' + this.code + '</td>';
tableContent += '<td>delete</td>';
tableContent += '</tr>';
});
// Inject the whole content string into our existing HTML table
$('#winnerList table tbody').html(tableContent);
});
};
I have read this question, but I haven't figured out how to make it work within Node.js
For GET requests, parameters are usually passed in the url's query string http://en.wikipedia.org/wiki/Query_string . In this case, your AJAX URL should be
'/users/winnerlist?start=20140621&end=20140623'
Then, on the server side, you can use the variables as:
req.query.start //This equals "20140621"
req.query.end // This equals "20140623"

Parsing JSON with AJAX - show random item of the JSON and update after an amount of time

I'm able to parse JSON with ajax, but at the moment it shows all the names out of the JSON.
I want only one name viewed and after an amount of time I want another one viewed and so on..
Ajax code:
$(document).ready(function(){
parseJson();
});
function parseJson(){
$.ajax({
url : 'data/members.json',
dataType : 'json',
success : function(data) {
succes(data);
},
error: function(){
window.alert("error");
}
});
};
function succes(dataObj){
var counter = 1;
$.each(dataObj.Members.Member, function(indexData, valueData){
var htmlString = "";
htmlString += '<article class="memberInfo" data-object="' + counter + '">';
htmlString += "<div class=''><p>" + valueData.Firstname + ' ' + valueData.Surname + "</p></div>";
htmlString += "</article>";
$("#members").append(htmlString);
counter++;
});
}
Rather than use .append you can use .html and set a staggering timeout so that it cycles through the names that get displayed:
var timer = 0;
$.each(...
setTimeout(function () {
var htmlString = "";
/* snip */
$("#members").html(htmlString);
}, timer + (indexData * 2000));
});

Resources