Parsing links from an XML files with JavaScript - javascript

To display my latest blog-posts on a different page I want to parse the rss-feed from the blog and then generate elements with it.
I first tried to parse a fixed .xml file for which I wrote the following code:
var maxBlogposts = 5;
var blogPosts = 0;
$.get("rss.xml", function(data) {
$(data).find("item").each(function() {
if(blogPosts === maxBlogposts) return;
var el = $(this);
//Only display 3 posts on small devices.
var extra = (blogPosts >= 3) ? "not-small 12u(small)" : "12u(small)";
var div = $('<div class="6u ' + extra + '" class="blog-entry"></div>');
var h = $('<h4>' + el.find("title").text() + '</h4>');
var description = el.find("description").text().replace('[…]', '[…]');
var p = $('<p>' + description + '</p>');
div.append(h);
div.append(p);
$('#blog').append(div);
blogPosts++;
});
});
This worked perfectly fine. Now I want to parse the actual rss-feed. For this I wrote a PHP script which simply gets the feed and echos it.
<?php
$rss = file_get_contents('http://xn--der-grne-baum-1ob.net/feed/');
die($rss);
?>
And again I get the correct XML file on the frontend.
The problem I have is that now my code is no longer working. Getting the description was failing as well as the links. I fixed the description by accessing
el.find(description")[0].innerHTML
However I can't seem to get the links to work. The data returned from the PHP file contains a node with the link in it. The "el"-element also contains children named "link" but those no longer contain the actual link.
I feel like the links may get "escaped" during parsing? At least that is the only reason i could think of that would result in what I am observing.
The XML I am parsing comes from http://xn--der-grne-baum-1ob.net/feed/

Try
var maxBlogposts = 5
, blogPosts = 0;
$.get("https://query.yahooapis.com/v1/public/yql?q=select"
+ " * from feed where url='http://xn--der-grne-baum-1ob.net/feed/'")
.then(function(data) {
$(data.documentElement).find("results item")
.each(function() {
if(blogPosts === maxBlogposts) return;
var el = $(this);
//Only display 3 posts on small devices.
var extra = (blogPosts >= 3) ? "not-small 12u(small)" : "12u(small)";
var div = $('<div class="6u ' + extra + '" class="blog-entry"></div>');
var h = $('<h4>' + el.find("title").text() + '</h4>');
var description = el.find("description").text().replace('[…]', '[…]');
var p = $('<p>' + description + '</p>');
div.append(h);
div.append(p);
$('#blog').append(div);
blogPosts++;
});
}, function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="blog"></div>
See YQL Console

Related

Can't figure out why my phantomJS script isn't showing the status and taking a picture of the page

I am not getting a status of the website nor an error when executing the code when using the URL that is being generated. However, when I use 'http://google.com', the status shows and it takes a screenshot of the page. The URL that is being used is a correct one, when I open the URL in browser it is the Page I want. It seems like the page is unreachable but I am not getting an error nor a status update.
var size = 9;
var model = 'CQ2626';
function URL(size, model){
var baseSize = 580;
var shoeSize = size - 6.5;
shoeSize *= 20;
rawSize = shoeSize + baseSize;
var URL = 'http://www.adidas.com/us/' + model + '.html?forceSelSize=' + model + '_' + rawSize;
return URL
};
console.log(URL(size, model));
var page = require('webpage');
var webPage = page.create();
webPage.open(URL(size, model), function(status){
console.log("Status: " + status);
if(status === "success") {
webPage.render('example.png');
}
phantom.exit();
});

Unable to receive parameter in query string when redirected to other page

Hi I am developing one application in java-script. I have two pages default.aspx and addnewitem.aspx. there is one html table in default.aspx and one button. When i click on button i want to redirect to addnewitem.aspx page. I have some parameters to send in query string. I am able to redirect to addnewitem.aspx but page not found error i am getting. I am not sure why i am getting page not found error. I am trying as below.
function getValues() {
var Title = "dfd";
var PrimarySkills = "fdfd";
var SecondarySkills = "dfdf";
var url = "http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=" + encodeURIComponent($(Title)) + "&PrimarySkills=" + encodeURIComponent($(PrimarySkills)) + "&SecondarySkills=" + encodeURIComponent($(SecondarySkills));
window.location.href = url;
}
I am checking querystring in addnewitem.aspx as below.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["Title"] != null && queryString["PrimarySkills"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Title:</b> " + queryString["Title"] + " <b>PrimarySkills:</b> " + queryString["PrimarySkills"] + " <b>SecondarySkills:</b> " + queryString["SecondarySkills"];
$("#lblData").html(data);
alert(data);
}
});
</script>
"http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=%5Bobject%20Object%5D&PrimarySkills=%5Bobject%20Object%5D&SecondarySkills=%5Bobject%20Object%5D"
I tried lot to fix this. May i know where i am doing wrong? Thanks for your help.
You should use the relative path in your url instead of hard coding the entire folder structure, which is probably incorrect since you are getting a 404. And you need to change the url every time you publish the site to the hosting enviroment when you hard code it like that.
So change
var url = "http://sites/APPSTEST/JobRequisitionApp/Pages/AddNewItem.aspx?Title=...
into
var url = "/AddNewItem.aspx?Title=...
if both the pages are in the same folder. Should AddNewItem.aspx be located in the Pages folder, you have to add that folder of course: var url = "/Pages/AddNewItem.aspx?Title=...

Why does the Flickr public feed API return "undefined" before displaying photo results when accessed by jQuery?

I started working with APIs/Ajax/JSON recently and began a small project to test my knowledge.
I made a simply website where you type a word into a form and it brings back Flickr photos associated with the word.
It works pretty well, but it always includes a simple "undefined" before the first photo which messes with the display of the first row of pictures.
An example can be seen here, simply search for a photo tag and you'll see what I'm talking about:
http://codepen.io/anon/pen/jPExNm
Here is the related jQuery:
$('form').submit(function (evt) {
evt.preventDefault();
// the AJAX part
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
var query = $('#photoQuery').val();
var flickrOptions = {
tags: query,
format: "json"
};
function displayPhotos(data) {
var photoHTML;
$.each(data.items,function(i,photo) {
photoHTML += '<div class="photo">';
photoHTML += '<a href="' + photo.link + '" class="image">';
photoHTML += '<img src="' + photo.media.m + '"></a></div>';
}); // end each
$('#photoGallery').html(photoHTML);
}
$.getJSON(flickerAPI, flickrOptions, displayPhotos);
}); // end submit
I haven't found any errors related to this in the Javascript console and couldn't find anything like this while Googling, so I'm turning to StackOverflow. Thank you for any and all help.
Because
var photoHTML;
is the same thing as
var photoHTML = undefined;
Basic example of what you are doing
var str;
str = str + "123"; // undefined + "123" = "undefined123";
You need to set it to an empty string
var photoHTML = "";

Using HTML Tags in Wordpress Page. Getting Error: "Unexncaught SyntaxError..."

I am retrieving data from Parse in my Wordpress page fine. I can append the names of my objects into a page in Wordpress, but as soon as a try to append a HTML tag like <h1> or <p>, I get an error within my Chrome console:
Uncaught SyntaxError: Unexpected token ILLEGAL
Below is the code within my wordpress page that works without errors:
<div id="list1"><h1>Beer List</h1></div>
<div id="list2"><h1>Tap List</h1></div>
<script type="text/javascript">
if (typeof jQuery != 'undefined') {
Parse.initialize("", "");
var Objs = Parse.Object.extend("Obj");
var query = new Parse.Query(Objs);
query.ascending("name");
query.find({
success: function(results) {
var obj1String = '';
var obj2String = '';
for(var i=0;i<results.length;i++)
{
var object = results[i];
obj1String= obj1String +' '+object.get('name')+'</br>';
if(object.get('isObj2') == true){
obj2String = obj2String +' '+object.get('name')+'</br>';
}
}
jQuery( "#list1" ).append( obj1String );
jQuery( "#list2" ).append( obj2String );
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
</script>
But when I add, for example a tag to one of my objStrings, I get the error. i.e.:
obj1String= obj1String +'<h1>'+object.get('name')+'</h1></br>';
Here is how the page is rendering, any why the error is happening. It seems to be adding a line break when it sees those tags:
for(var i=0;i<results.length;i++)
{
var object = results[i];
obj1String= obj1String +' //line break added here
<h1>'+object.get('name')+'</h1>
<p></br>';
if(object.get('isObj2') == true){
objString = obj2String +' '+object.get('name')+'</br>';
}
I have see other threads for this error (i.e. here). But I could not get any suggestions there to work.
Any help would be greatly appreciated, thanks!
I've had a similar problem to this before and I fixed it by making sure all the HTML tags in the JavaScript are on the same line.
As for wordpress template files you can read more about it here http://codex.wordpress.org/Page_Templates. Simply it will allow you to use a PHP file as a template to display that page.

how to append if found, and replace if not found at all? (xml find.each loop)

I'm trying to search a string value in an xml file, and then append to a div if the string value is found. If not found at all, then I need to display an error text in the same div that the search term was not found.
This is basically supposed to be a search page which loads the searched items into div content.
Currently my content is loading fine. The searched term if found loads all the corresponding divs from the xml, but I've been unable to display an error if the search term was not found.
My XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<item>
<animal_id>1_1</animal_id>
<animal_title>Sparrow</animal_title>
<animal_generic>Birds 1</animal_generic>
<animal_category>Birds</animal_category>
<animal_code>a1</animal_code>
<animal_img>http://i.imgur.com/R0754lr.png</animal_img>
<animal_url>1_1_Animals1.html</animal_url>
</item>
<item>
<animal_id>1_2</animal_id>
<animal_title>Crow</animal_title>
<animal_generic>Birds 2</animal_generic>
<animal_category>Birds</animal_category>
<animal_code>b2</animal_code>
<animal_img>http://i.imgur.com/R0754lr.png</animal_img>
<animal_url>1_2_Animals2.html</animal_url>
</item>
<item>
<animal_id>1_3</animal_id>
<animal_title>Parrot</animal_title>
<animal_generic>Birds 3</animal_generic>
<animal_category>Birds</animal_category>
<animal_code>c3</animal_code>
<animal_img>http://i.imgur.com/R0754lr.png</animal_img>
<animal_url>1_3_Animals3.html</animal_url>
</item>
</items>
HTML
<div class="list-h">
</div>
Javascript
var s_string = 'bird';
$.ajax({
url: 'https://dl.dropboxusercontent.com/u/27854284/Stuff/Online/XML_animals.xml', // name of file you want to parse
dataType: "xml",
success: function parse(xmlResponse){
$(xmlResponse).find("item").each(function() {
var pr_id = $(this).find("animal_id").text();
var p_title = $(this).find("animal_title").text();
var p_category = $(this).find("animal_category").text();
var p_code = $(this).find("animal_code").text();
var p_img = $(this).find("animal_img").text();
var p_url = $(this).find("animal_url").text();
var p_gen_name = $(this).find("animal_generic").text();
var p_xml_string = p_title + p_gen_name, results_string = '', error;
if(s_string)
var s_string2 = s_string.replace("%20"," ");
//console.log(p_xml_string + s_string2);
if(p_xml_string.toLowerCase().indexOf(s_string2) > -1){
//console.log("FOUND : " + p_title);
results_string = '<div class="item"><div class="item-h"><a class="item-anchor" href="' + p_url + '"><div class="item-image"><img class="item-image-first" src="' + p_img + '" alt=""><div class="item-meta"><h2 class="item-title">' + p_title + '</h2><span class="item-arrow"></span></div></div></a></div></div>';
found_string = true; //// KEEP VALUES = TRUE OR FALSE IN AN ARRAY...GLOBAL ARRAY, AND THEN SEARCH THAT ARRAY FOR TRUE. IF ALL FALSE, SHOW ERROR.
}
if(found_string){
$('.list-h').append(results_string);
$('<div id="error_div"></div>').text("found");
}
}); //xmlResponse .each function end.
}, error: function(){console.log('Error: Animals info xml could not be loaded.');}
});
// START OF NOT FOUND SEARCH SCRIPT
$(window).load(function(){
var error_found = $('#error_div').text(); console.log(error_found);
setTimeout(function(){
if(error_found != 'found'){
var results_string = '<center>Your Search Query "<b>' + $.url().param('q').replace("%20"," ") + '" was not found!</b> Maybe you entered an invalid search query.</center>';
$('.list-h').append(results_string); }
}, 0);
});
// END OF NOT FOUND SEARCH SCRIPT
And here's the js fiddle with complete XML url: http://jsfiddle.net/mohitk117/B89Ms/
Please could someone help me out regarding this? Thanks!
Some changes may sort out your problem
Add a div in your html
<div id="error_div"></div>
Change below code
if (s_string) var s_string2 = s_string.replace("%20", " ");
//console.log(p_xml_string + s_string2);
if (p_xml_string.toLowerCase().indexOf(s_string2) > -1) {
to
var s_string2='';
if (s_string) s_string2 = s_string.replace("%20", " ");
if (s_string2 && p_xml_string.toLowerCase().indexOf(s_string2) > -1) {
Change found_string code like,
if (found_string) {
$('.list-h').append(results_string);
$('#error_div').text("found");
}
Optionally add css for error_div
#error_div {
color:red;
}
Live Demo
Updated success code
var found_string = false; // define found_string globally
$(xmlResponse).find("item").each(function () {
var pr_id = $(this).find("animal_id").text();
var p_title = $(this).find("animal_title").text();
var p_category = $(this).find("animal_category").text();
var p_code = $(this).find("animal_code").text();
var p_img = $(this).find("animal_img").text();
var p_url = $(this).find("animal_url").text();
var p_gen_name = $(this).find("animal_generic").text();
var p_xml_string = p_title + p_gen_name,
results_string = '',
error;
var s_string2 = '';
if (s_string) s_string2 = s_string.replace("%20", " ");
if (s_string2 && p_xml_string.toLowerCase().indexOf(s_string2) > -1) {
//console.log("FOUND : " + p_title);
results_string = '<div class="item"><div class="item-h"><a class="item-anchor" href="' + p_url + '"><div class="item-image"><img class="item-image-first" src="' + p_img + '" alt=""><div class="item-meta"><h2 class="item-title">' + p_title + '</h2><span class="item-arrow"></span></div></div></a></div></div>';
found_string = true; //// KEEP VALUES = TRUE OR FALSE IN AN ARRAY...GLOBAL ARRAY, AND THEN SEARCH THAT ARRAY FOR TRUE. IF ALL FALSE, SHOW ERROR.
}
if (found_string) { // if found then append in list
$('.list-h').append(results_string);
}
}); //xmlResponse .each function end.
if (found_string) { // if found then empty error div
$('#error_div').text("");
} else { // else show error text or not found
$('#error_div').text("not found");
}
Updated Found Demo and Not Found Demo
I'm a bit uncertain of how everything fits together because the javascript code is not self-explanatory. But, can you start by addressing this issue here...?
if(s_string)
var s_string2 = s_string.replace("%20"," ");
//console.log(p_xml_string + s_string2);
if(p_xml_string.toLowerCase().indexOf(s_string2) > -1){
s_string2 variable is out of scope when you use it in this expression...
if(p_xml_string.toLowerCase().indexOf(s_string2) > -1){
What were you trying to do there? The expression above will always evaluate to false because s_string2 is undefined. In other words, whatever processing you are doing inside that if block will never be reached
Again, this variable is instantiated and disposed at the very same time...
if(s_string)
var s_string2 = s_string.replace("%20"," "); //<--- This variable's lifecycle ends here
and, this expression will always be false until you address the variable issue above...
if(p_xml_string.toLowerCase().indexOf(s_string2) > -1)

Categories

Resources