Loop through multiple RSS sources and outputting in different divs? - javascript

I want to loop through two (possibly more in the future) RSS-feeds and put them in different container divs. I started out with following this question: JQuery Fetch Multiple RSS feeds.
Here's my code.
var thehtml = '';
$(function () {
var urls = ['http://www.gosugamers.net/counterstrike/news/rss', 'http://www.hltv.org/news.rss.php'];
for (var i = 0; i < urls.length; i++) {
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(urls[i]),
dataType: 'json',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function (xml) {
values = xml.responseData.feed.entries;
console.log(values);
$.each(values, function(idx, value){
thehtml += '<a class="news-item" href="' + value.link + '" title="' + value.title +'" target="_blank"><p>' + value.publishedDate + '</p><h3>' + value.title + '</h3></a><hr>';
});
$("#content_1").html(thehtml);
}
});
}
});
I load two RSS feeds and in the console output I can see the two data arrays.
Right now I use $(#content_1).html(thehtml); to output the feed data as HTML in a container div, #content_1.
What I want to do is to put the first RSS-feed into #content_1 and the second into #content_2. I tried using .slice(0,10) but couldn't get it to work and it doesn't seem like the best way.

Here is the interval in place. The container content will empty to display the new data.
Update: Ajax results target content_1 and content_2 with optional second method.
$(function () {
function GetFeeds(){
var urls = ['http://www.gosugamers.net/counterstrike/news/rss', 'http://www.hltv.org/news.rss.php'];
urls.forEach(function(Query){
$.ajax({
type: "GET",
url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q='+encodeURIComponent(Query),
dataType: 'json',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function(xml) {
//--Target ID's By content_1/2
var Content=parseInt(urls.indexOf(Query))+1;
$("#content_"+Content).html('');
$.each(xml.responseData.feed.entries, function(idx, value){
$("#content_"+Content).append('<a class="news-item" href="' + value.link + '" title="' + value.title +'" target="_blank"><p>' + value.publishedDate + '</p><h3>' + value.title + '</h3></a><hr>');
});
//---------------
//--Target ID's By Domain (Method Two)
/*
$("#"+Query.split('.')[1]).html('');
$.each(xml.responseData.feed.entries, function(idx, value){
$("#"+Query.split('.')[1]).append('<a class="news-item" href="' + value.link + '" title="' + value.title +'" target="_blank"><p>' + value.publishedDate + '</p><h3>' + value.title + '</h3></a><hr>');
});
-----------------------------------*/
}
});
});
}
//Call GetFeeds every 5 seconds.
setInterval(GetFeeds,5000);
//Page is ready, get feeds.
GetFeeds();
});
#content_1{float:left;width:40%;overflow:hidden;border:solid 2px blue;}
#content_2{float:right;width:40%;overflow:hidden;border:solid 2px yellow;}
/* Method Two Styles
#gosugamers{float:left;width:40%;overflow:hidden;border:solid 2px green;}
#hltv{float:right;width:40%;overflow:hidden;border:solid 2px red;}
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="content_1"></div>
<div id="content_2"></div>
<!-- Method Two Elements
<div id="gosugamers"></div>
<div id="hltv"></div>
-->
If you don't understand any of the source code above please leave a comment below and I add any necessary comments/notes. Appreciation is shown by marking answers
I hope this helps. Happy coding!

Related

Update: How do I dynamically populate a list with data from a JSON file?

I want to dynamically populate a list with elements from a JSON file. The idea is to switch the test_ID in the list with the actual object from the JSON file. How do I do this?
JSON file
[
{
"id": "a",
"test": "Java",
"testDate": "2016-08-01"
},
{
"id": "b",
"test":"JavaScript",
"testDate": "2016-08-01"
}
]
jQuery
$(function(){
$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
});
$("#test_ID").empty(); //emtpy the UL before starting
$.each(arr_json, function(i, v, d) {
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
});
}
});
});
HTML
<li id="test_ID"></li>
I do receive a couple of errors. The Line:
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
gives the following error: invalid number of arguments and unclosed String literal.
I am also unsure of how to identify to specific elements in the JSON file.
Update
I would like if the list element was in this format "Java 2016-08-01" and "JavaScript 2016-08-01". Thank you!
You have a couple of errors in your javascript. See the corrected version below:
$(function(){
$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
$("#test_ID").empty(); //emtpy the UL before starting
// **************** correction made to the line below ***********************
$.each(result, function(i, v, d) {
// **************** correction made to the line below ***********************
$("#test_ID").append('<li id="' + v.id + '">' + v.test + ' ' + v.testDate + '</li>'); // correction made here
});
}
});
});
I did a quick fiddle. I don't quite understand what you're doing with v.test being unmarked inside the HTML tags so I did not include it. I used minimal JQuery to avoid complexity.
https://jsfiddle.net/ndx5da97/
for (record in data) {
$("#test_ID").append('<li id="' + data[record].id + '">' + data[record].testDate + '</li>');
}
Hope this helps!

JSON to HTML not rendering into HTML via ID

I am using PHPstorm IDE and i'm trying to render the following JSON and it gets stuck showing only the <ul></ul> without spitting the <li>'s into HTML the each function. Any idea what could be the issue?
thanks.
Script.js:
$(function(){
$('#clickme').click(function (){
//fetch json file
$.ajax({
url:'data.json',
dataType: 'json',
success: function(data){
var items = [];
$.each(data, function (key, val) {
items.push('<li id=" ' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'tasks',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function(){
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
And the JSON:
{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}
My HTML is just an a href that spits out the click ID:
Get JSON
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
<button>Get JSON data</button>
By Using this Method You can Easily get Your JSON value In HTML
Try this one :)
$.ajax({
url: 'data.json',
dataType: 'json',
success: function(data){
var html = "<ul>";
items = data.map(function(obj){
html += "<li id='" + obj.id + "'>" + obj.mesi + "</li";
});
html += "</ul>";
$('body').append(html);
I would try with some like this
$(function(){
$('#clickme').click(function (){
//fetch json file
$.ajax({
url:'data.json',
dataType: 'json',
success: function(data){
// uncomment line below if data is a single JSON
// data = [data]
var items = [];
// we create a list where we will append the items
var list = document.createElement("ul");
data.forEach(function(item){
// we create a list item
var listItem = document.createElement("li");
// we set the attributes
listItem.setAttribute("id", item.id ); // item.id or the property that you need
// we add text to the item
listItem.textContent = item.mesi;
// We append the list item to the list
list.appendChild(listItem);
});
// we append the list to the body
$("body").html(list);
},
statusCode: {
404: function(){
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
Try like this:
success: function(data){
var items = '';
$.each(data, function (key, val) {
items += '<li id=" ' + key + '">' + val + '</li>';
});
ul = $('<ul/>').html(items);
$('body').append(ul);
}
for multiple objects
success: function(datas){
var items = '';
$.each(datas, function (i,data) {
$.each(data, function (key, val) {
items += '<li id=" ' + key + '">' + val + '</li>';
});
});
ul = $('<ul/>').html(items);
$('body').append(ul);
}
output
<ul>
<li id=" id">1</li>
<li id=" mesi">mesima 0</li>
<li id=" done_bool">1</li>
<li id=" id">2</li>
<li id=" mesi">mesima 1</li>
.
.
</ul>
Try like this:
$(function() {
$('#clickme').click(function() {
// fetch json file
$.ajax({
url : 'data.json',
dataType : 'json',
// please confirm request type is GET/POST
type : 'GET',
success : function(data) {
// please check logs in browser console
console.log(data);
var ulHtml = "<ul>";
$.each(data, function(key, obj) {
ulHtml += '<li id="' + obj.id + '">' + obj.mesi + '</li>';
});
ulHtml += "</ul>";
// please check logs in browser console
console.log(ulHtml);
$('body').append(ulHtml);
},
error : function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
alert(textStatus);
}
});
});
});
<button id="clickme">Get JSON data</button>
I log json data and created ul html, Please check logs in browser console
I'm not sure how you want to output each item, so I made a simple suggestion, you can easily change the HTML to what you need. Here is working code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
Get JSON
<script>
$(function() {
$('#clickme').click(function() {
//fetch json file
$.ajax({
url: 'data.json',
dataType: 'json',
success: function(data) {
var items = [];
$.each(data, function(key, val) {
// the HTML output for each item
var done = (val.done_bool === '1') ? 'true' : 'false';
items.push('<li id=" ' + val.id + '">' + val.mesi + ': ' + done + '</li>');
});
$('<ul/>', {
'class': 'tasks',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function() {
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
</script>
</body>
</html>
data.json
[{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}]
I also created a __jsfiddle__ so you can test it directly. (The AJAX call is simulated with the Mockjax library): https://jsfiddle.net/dh60nn5g/
Good to know:
If you are trying to load the JSON from another domain, you may need to configure CORS (Cross-origin resource sharing):
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Isn't this supposed to be a GET request? i think you are missing the method on your Ajax request. You should add
method: 'GET'
to your ajax request. I think this is a big deal in making ajax request.

Using slice() to only return the first 5 results

Currently I have a site that when a button is clicked it returns the lastest movies and tv shows that are airing.
Right now the api I am using returns a whole page of values up to 20 results from my research of the api there is no limit function all i want to do is have 5 of those results be returned
I have been told that the slice() function may work.
Also any other why that you think my work would be nice aswell if you can figure out another way
I have included a jsfiddle but removed my api key
jsfiddle - http://jsfiddle.net/xvTe9/
Here's all my code just without my api key
<html>
<head>
<title>Sample Seach</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'movie/now_playing',
input,
movieName,
key = '?api_key=API KEY HERE';
$('#search').click(function() {
var input = $('#titlesearch').val(),
movieName = encodeURI(input);
$.ajax({
url: url + mode + key + '&query='+movieName' ,
dataType: 'jsonp',
success: function(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td class="results-img"><img src="http://image.tmdb.org/t/p/w500' + value.poster_path +'" alt="" width="130" height="150"></td><td class="results-title"><h4>' + value.original_title + '</h4></td></tr>';
});
$('#searchresult').html(table);
}
});
});
});
// tv show search
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'tv/on_the_air',
input,
tvName,
key = '?api_key=API KEY HERE';
$('#search').click(function() {
var input = $('#titlesearch').val(),
tvName = encodeURI(input);
$.ajax({
url: url + mode + key + '&query='+tvName,
dataType: 'jsonp',
success: function(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td class="results-img"><img src="http://image.tmdb.org/t/p/w500' + value.poster_path +'" alt="" width="130" height="150"></td><td class="results-title"><h4>' + value.original_name + '</h4></td></tr>';
});
$('#searchresulttv').html(table);
}
});
});
});
</script>
<script text="text/javascript">
// When the more button is click this runs a search using the title of the movie it is next to
$('.results-img').live('click', '.results-img', function() {
getImdbInfo( $(this).closest('tr').find('.results-title').text());
});
//The function below takes the entered title and searchs imdb for a match then it displays as followed
function getImdbInfo(Title) {
var url = "http://www.omdbapi.com/?t=" + Title + "&plot=full";
$.ajax({
url: url,
cache: false,
dataType: "jsonp",
success: function(data) {
var str = "";
str += "<h2><center>Title :" +data.Title+ "</center></h2>";
str += "<center><img src='" + data.Poster + "' /></center><br />";
str += "<h4><center>Plot :</center></h4><p>" +data.Plot+ "</p>";
$("#chosenresult").html(str);
},
error: function (request, status, error) { alert(status + ", " + error); }
});
}
</script>
</head>
<body>
<center>
<h1>Movie and Tv Search</h1>
<button id="search">Search</button>
</center>
<div id="chosenresult"></div>
<div id="searchresult" style="float:left;"></div>
<div id="searchresulttv" style="float:right;"></div>
</body>
</html>
Screenshot of results that i want just the 5
Use slice to first reduce the array which must be iterated in the callback function of ajax.
var results = data.results.slice(0,5);
$.each(results, function( key, value ) {
table += '<tr><td class="results-img"><img src="http://image.tmdb.org/t/p/w500' + value.poster_path +'" alt="" width="130" height="150"></td><td class="results-title"><h4>' + value.original_name + '</h4></td></tr>';
});
Assuming you've stored the results in an array,
arr.slice(0,5)
will return the first five elements.
Using your current $.each you could do:
$.each(data.results, function (index, value) {
table += '<tr>
<td class="results-img">
<img src="http://image.tmdb.org/t/p/w500' + value.poster_path + '" alt="" width="130" height="150">
</td>
<td class="results-title">
<h4>' + value.original_name + '</h4>
</td>
</tr>';
return (index !== 6);
});

how to show the loader dynamically until all the image load in jquery mobile phonegap listview

am having trouble to showing loader untill all the image is load in the listview.the following code is used in my app.it shows the loader untill all the image is load but the problem is , append the last src value to all the image attribute src.please help me.
$.ajax({
url: "http://www.some.com/",
type: 'POST',
data: param,
dataType: "jsonp",
success: function (result) {
$.each(result.results, function (k, v) {
var searchPic = "http://www.some.com" + $.trim(v.eventIcon);
var localarray = new Array();
var c = v.eventText;
strs = c.slice(0, 60);
$('[data-role="listview"]').append('<li> ' + '<img alt="img" class="pic1" src=" ">' + '<h4 >' + v.eventTitle + '</h4>' + '<p>' + strs + '...' + '</p></li>');
$('[data-role="listview"]').listview('refresh');
imgload(searchPic);
});
$('[data-role="listview"]').append('<li id="no-results">There is no record found based on your search criteria, please refine your search.</li>');
}
});
function imgload(tx) {
$('.pic1').load(function () {
$.mobile.loading('hide');
}).attr('src', tx);
}
});

Use $.each and if with $.getJSON

Me and $.each aren't good friends, I can't seem to figure out how I should use this statement to print all my data in my JSON file. Another problem is the if statement, I tried it in many ways, but whatever I do, no data is being printed.
My JSON file
[
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"exp1_index.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"exp2_index.html"
}
]
My $.getJSON script
<script type="text/javascript">
function read_json() {
$.getJSON("home.json", function(data) {
var el = document.getElementById("kome");
el.innerHTML = "<td><div class='dsc'>" + data.expo + "<br><em>" + data.datum + "</em></div></td>";
});
}
</script>
So how would I integrate the $.each statement and seperate from that, the if statement?
Try this
$.getJSON("home.json", function (data) {
var html = '',
el = document.getElementById("kome");
$.each(data, function (key, val) {
html += "<td><div class='dsc'>" + val.expo + "<br><em>" + val.datum + "</em></div></td>";
});
el.innerHTML = html;
});
Something like this?
<script type="text/javascript">
function read_json() {
$.getJSON("home.json", function(data) {
var html = '';
$.each(data, function(i, record) {
html += '' +
'<td>' +
'<a href="' + record.link + '" data-ajax="false">' +
'<img src="' + record.img + '">' +
'<div class="dsc">' +
record.expo + '<br>' +
'<em>' + record.datum + '</em>' +
'</div>' +
'</a>' +
'</td>';
});
$('#kome').html(html);
});
}
</script>
Note: I haven't tested this, so there may be a few syntax errors (mostly concerned about the quotes in the string concatenation).
I will note that you don't need jQuery's $.each for this; you can use a basic for-loop:
for (var i = 0; i < data.length; i++) {
var record = data[i];
... stuff...
}
jQuery's .each() is really useful when iterating over elements in the DOM, though. For example, if you wanted to iterate over the elements with class dsc, you could do:
$('.dsc').each(function(i, dsc) {
// Do stuff to the $(dsc) element.
});
Also, you might as well use jQuery's selectors (the $('#kome')) if you're going to use jQuery.
jQuery's API usually has solid examples for stuff; this is one such case.
$.each can iterate arrays [] or objects {}, your json contains both, so first you need to tackle array, that gives you an object on each iteration. Then you can access its properties.
jQuery each documentation
Second thing: to append to innerHTML use "+=" not "=" or you will reset html on each iteration.
var el = document.getElementById("kome");
$.getJSON('ajax/test.json', function(data) {
$.each(data, function(n, linkData) {
el.innerHTML += '' + linkData.expo + '';
});
}

Categories

Resources