I am using GoogleFeed API to display an RSS feed as HTML:
var feedcontainer=document.getElementById("feeddiv")
var feedurl="MY FEED URL"
var feedlimit=20
var rssoutput=""
function rssfeedsetup(){
var feedpointer=new google.feeds.Feed(feedurl) //Google Feed API method
feedpointer.setResultFormat(google.feeds.Feed.MIXED_FORMAT)
feedpointer.setNumEntries(feedlimit) //Google Feed API method
feedpointer.load(displayfeed) //Google Feed API method
}
function displayfeed(result){
if (!result.error){
var thefeeds=result.feed.entries
for (var i=0; i<thefeeds.length; i++)
rssoutput+="<a href='" + thefeeds[i].link + "' style='text-decoration:none'>" + "<h1 class='pub'>" + thefeeds[i].title + "</h1>" + "</a>" + new Date(thefeeds[i].publishedDate) + thefeeds[i].content + "<p class='text-small-hilite'><a href='" +thefeeds[i].link + "'>" + "Read full post" + "</a></p>"
rssoutput+=""
feedcontainer.innerHTML=rssoutput
}
else
alert("Error fetching feeds!")
}
window.onload=function(){
rssfeedsetup()
}
I want to also display as HTML a CDATA element inside my tag . I've tried .xmlNode.getElementsByTagName but that hasn't worked.
<item>
<title>
MY TITLE
</title>
<link>MY URL</link>
<comments>MY URL</comments>
<pubDate>Fri, 17 Oct 2014 19:06:53 +0000</pubDate>
<dc:creator>
<![CDATA[ MY AUTHOR ]]>
</dc:creator>
Is it possible to get the text within the CDATA "MY AUTHOR" to display as HTML?
That tag has the dc namespace, so you could use getElementsByTagNameNS method inside your for-loop like this:
var creator = thefeeds[i].xmlNode.getElementsByTagNameNS(
'http://purl.org/dc/elements/1.1/', 'creator')[0].innerHTML;
But if you just want contents of dc:creator, it is probably the same as thefeeds[i].author. The Feed API's JSON documentation can be helpful.
Tip: use your browser's developer tools and set a breakpoint inside your for-loop, then you can see what the object contains:
Related
I'm working on a small project where I am wanting to randomly pull one row of a google sheet, and then use that data in an HTML table.
For now, my solution has been first to use javascript to make a random number, then generate an HTML table from google sheets for just that row using this method. So, I end up with a URL for an HTML table with just header row, and a random row of data, similar to this. Then I just embed that table as an object in my HTML page. This is the gist of it:
< script >
window.onload = function() {
var albumno = Math.random() * 408;
var albumno = Math.round(albumno);
var albumurl = "https://docs.google.com/spreadsheets/d/UNIQUE-DOCUMENT-ID/gviz/tq?tqx=out:html&tq=SELECT%20B%2C%20D%2C%20E%2C%20F%2C%20G%20WHERE%20A%20MATCHES%20%27" + albumno + "%27&gid=1739065700";
document.getElementById("output").innerHTML = "ALBUM NUMBER: " + albumno + ".";
document.getElementById("albumpath").innerHTML = '<object align="middle" data="' + albumurl + '">';
};
</script>
There are two major drawbacks. First, the table cannot be (easily) formatted when embedded as an object. Second, my google sheet is a list that is added to weekly, and therefore I have to manually adjust the limits of the random value generated in my javascript.
Is there a way to do this more effectively in Javascript? Perhaps by scraping the full table, and then randomly selecting a row of data, which can be used in an proper HTML table (i.e. not embedded as an object)? Or maybe there exists a google sheets API that would help me?
UPDATE:
I have managed to write a quick function in Google Apps Script that picks the random row of data. I have figured two ways to output the data, option 1 as an array, or option 2 as HTML code for a table. Now how do I call this function in my HTML page, and make use of these data?
}
function randomalbum() {
//get spreadsheet
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/[DOCID]/edit#gid=1');
var sh = ss.getSheetByName("Pick List");
//find last album
var Fvals = sh.getRange("F:F").getValues();
var Flast = Fvals.filter(String).length;
var colnum = sh.getRange(2, 1, Flast).getValues();
var albumlast = Math.max.apply(null, colnum)-1;
//pick random row (note the row an album is in is 1 more than the album no.)
var rowrand = Math.round(Math.random()*(albumlast+1));
//extract data of interest
var albumrand = rowrand -1;
var pick = sh.getRange(rowrand, 5).getValues();
var artist = sh.getRange(rowrand, 6).getValues();
var title = sh.getRange(rowrand, 7).getValues();
//make array (option 1)
var array = [albumrand, pick, artist, title];
return array;
//make HTML string (option 2)
var HTMLString = " <table style='width:100%'>"
+ "<tr>"
+ "<th>Album No.</th>"
+ "<th>Picked By</th>"
+ "<th>Artist</th>"
+ "<th>Artist</th>"
+ "</tr>"
+ "<tr>"
+ "<td>" + albumrand + "</td>"
+ "<td>" + pick + "</td>"
+ "<td>" + artist + "</td>"
+ "<td>" + title + "</td>"
+ "</tr>"
+"</table>"
HTMLOutput = HtmlService.createHtmlOutput(HTMLString);
return HTMLOutput
}
Using a Google Sheets API without needing to run your own server: I remember following the suggestions in the following article to solve this a while ago.
https://coderwall.com/p/duapqq/use-a-google-spreadsheet-as-your-json-backend
You'll probably need another service to add CORS headers to the Google response because cors.io apparently no longer exists.
If you want to publish a web app out of the HTMLOutput returned by your function, you can do the following:
Rename your function to doGet: if you do this, Apps Script will run this function whenever a user visits the URL of the web app you are about to publish, as you can see here.
Remove the return array; in your code: the keyword return finishes current function, so the code will never return an HTMLOutput, and an array of values is not a valid object to return in this situation.
Publish the script as a web app: in your script editor, select Publish > Deploy as web app. Then select a Project version, choose under whose authorization the app should run and who should have access to it, and click Deploy. A URL will show app as Current web app URL. If you access that URL, you will see the HTML you created.
I hope this is of any help.
I have been trying to get this code to work:
if(searchResults != null){
for(var i=0; i < searchResults.length; i++){
var file = nlapiLoadFile(searchResults[i].getValue('custrecord_download_file'));
var result = searchResults[i].getText('custrecord_download_name');
var analytics = "onclick=\"ga(\'send\',\'event\','" + result + "');\"";
ulText += '<li><a href="'+ file.getURL() + '" target="_blank" ' + analytics + ' >' + searchResults[i].getText('custrecord_download_name') + '</a></li>';
}
}
ulText += '</ul>';
response.write('document.write(\'' + ulText + '\')');
}
But it breaks when it reaches the analytics variable since it has parameters with apostrophes. In the inspector I recieve:
document.write('<ul><li><a href="/core/media/media.nl?id=339181&c=685553&h=20e8a29160195ea985c6&_xt=.pdf" target="_blank" onclick="ga('send','event','Product Datasheet')" >Product Datasheet</a></li></ul>')
How can I still get the ga function working with 'send' like Google Analytics asks for without the script breaking once it reaches the first ga parameter. Thank you in advanced.
Escape your string with backlash like this:
document.write('<ul><li>Product Datasheet</li></ul>')
It should work and these could be a helpful: Escape strings in javascript
Try this:
var analytics = "onclick=\"ga(\'send\',\'event\',\'" + result + "\');\"";
Or you could try in ES6:
const analytics = `onclick=\"ga(\'send\',\'event\',\'${result}\');\"`;
edit: Problem solved! I was modifying the page before it was loaded so the script didn't actually do anything. I fixed it now and it works. Thanks for the help, I'll have to chalk this one up to being new to jQuery and it's weirdness.
Long story short I'm trying to make a webpage that dynamically takes Article titles, thumbnail images, descriptions, and links to them, and creates a nicely formatted list on the page. I'm trying to accomplish this in jQuery and HTML5.
Here is the sample data that I'll be using to dynamically populate the page. For now formatting isn't important as I can do that later after it works at all.
<script>
var newsTitles = ["If It Ain't Broke, Fix It Anyways"];
var newsPics = ["images/thumbnail_small.png"];
var newsDescs = ["August 14th 2015<br/><b>If It Ain't Broke</b><br/>Author: Gill Yurick<br/><br/> Sometimes, a solution isn't the only one. So how do we justify changes to systems that don't need to be fixed or changed? I explore various systems from other successful card games and how their approaches to issues (be they successes or failures in the eyes of the deisgners) can help us create EC."];
var newsLinks = ["it_aint_broke-gill_popson.html"];
var newsIndex = 0;
var newsMax = 1;
The section of code where I'm trying to use the contents of the arrays above to dynamically fill elements.
<td style="height:500px;width:480px;background-color:#FFF7D7;padding:20px" colspan=2 id="article">
<h1>Articles</h1>
<!-- the column for each news peice add an element with the thumbnail, the title and teh desc -->
<script>
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href="" newsLinks[i] + "">" + newsTitles[i] + "</h3>", "<img src=""newsPics[i] + "">","<p>" + newsDesc[i] + "</p>", ); $("div").append("hello");
}
</script>
<div id="articleList">
HELLO
</div>
</td>
Here is what it ends up looking like, I can post more info if needed as I am aware this may not be clear enough to fully explain my problem but I am unable to determine that. Thank you in advance.
try this
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href=""+ newsLinks[i] + "">" + newsTitles[i] + "</h3>, <img src=""+newsPics[i] + "">, <p>" + newsDescs[i] + "</p>" ); $("div").append("hello");
}
Concatation issue + typo for newsDescs
The following string is invalid html and is missing a +
"<h3 href="" newsLinks[i] + "">"
You need to use proper quotes for html attributes, not "e;
Try
"<h3 href='" + newsLinks[i] + "'>"
OR
"<h3 href=\"" + newsLinks[i] + "\">" // `\` used to escape same type quote
Personally I prefer opening/closing html strings with single quotes but either will work
Note tht you should be getting a syntax error thrown in dev tools console which would have helped you locate problems
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href='" + newsLinks[i] + "'>" + newsTitles[i] + "</h3>");
$("#articleList").append("<img src='" + newsPics[i] + "'>","<p>" + newsDesc[i] + "</p>" );
}
I have created a html web resource that I am showing when a ribbon button is clicked. On this popup I have a drop down list that I want to populate with a list of records that I have obtained using a fetchXml query.
My problem is that I have tried a few different ways to execute the query but it always comes back with errors. I'm guessing that the popup wont have the same range of functions that the parent form will have and so I will need to do something different to execute the query.
Currently I have it so that I have loaded an external script containing the functions needed to perform the fetch, but the code cannot see the CRM function of _HtmlEncode, and therefore fails.
Is there any way that I can get the popup to see the CRM functions? Or is there an alternate way of doing this?
EDIT: Some sample code
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:asp>
<head>
<title>Re-Assign</title>
<script type=text/javascript src="ClientGlobalContext.js.aspx"></script>
<script type=text/javascript src="http://crm/DEVCRM/WebResources:ts_/scripts/fetch_global.js"></script>
<script type=text/javascript>
function OnLoad_GetAreasAndConsultants() {
var fetchXml = '<fetch distinct="false" mapping="logical" output-format="xml-platform" version="1.0"><entity name="ts_solution_area"><attribute name="ts_solution_areaid"/><attribute name="ts_descriptor"/><attribute name="createdon"/> <order descending="false" attribute="ts_descriptor"/><filter type="and"><condition attribute="statecode" value="0" operator="eq"/></filter></entity></fetch>';
var fetchedRecords = FetchRecordsToolKit.Fetch(fetchXml);
if (fetchedRecords !== null) {
var areaList = document.getElementById("ddl_solution_area")
for (var i=0; i<fetchedRecords.length;i++) {
var name = fetchedRecords[i].getValue("ts_descriptor");
areaList.options[select.options.length] = new Option(name, i);
}
}
}
</script>
Thanks
I built something specifically for executing fetch within an HTML web resource.
https://github.com/paul-way/JCL/blob/master/jcl.js
Here's an example of using it:
var processProjectInfo = function (data) {
if (data.length > 0) {
// Set Project Header Information
$('#ProjectTitle').html(data[0].attributes.new_name.value);
$('#CompanyName').html(data[0].attributes.new_accountid.name);
}
};
var loadProjectInfo = function (guid) {
var fetchXML = " " +
"<fetch mapping='logical' count='10'>" +
" <entity name='new_project'>" +
" <all-attributes/>" +
" <filter>" +
" <condition attribute='new_projectid' operator='eq' value='" + guid + "' />" +
" </filter>" +
" </entity>" +
"</fetch>";
JCL.Fetch(fetchXML, processProjectInfo);
};
I have a web page where I want to display hotel reviews from the yelp.com API for a number of hotels.
I have managed to do this for one hotel, and it works perfectly displaying the data under that specific hotel's details on the page. However, how can I now multiply this process so that I have separate reviews for each hotel?
My web page can be seen at http://dev.bhx-birmingham-airport.co.uk/pages/hotels.php to get an idea of what I'm trying to do.
The source code I am using so far looks like:
<script>
function showData(data) {
$.each(data.businesses, function(i,business){
// extra loop
$.each(business.reviews, function(i,review){
var content = '<p>Review - ' + review.text_excerpt + ' Read more...</p>';
content += 'Rating - <img src="' + business.rating_img_url + '" />';
content += '<p>Date Added - ' + review.date + '</p>';
$(content).appendTo('#hilton');
});
});
}
$(document).ready(function(){
// note the use of the "callback" parameter
writeScriptTag( "http://api.yelp.com/business_review_search?"+
"term=hilton%20metropole"+
"&location=B26%203QJ"+
"&ywsid=[...]"+
"&callback=showData"); // <- callback
});
function writeScriptTag(path) {
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", path);
document.body.appendChild(fileref);
}
</script>
Your question is somewhat unclear.
I assume that you want to send multiple requests to Yelp and have them processed by different callback functions.
You can do that by making a buildCallback method that takes information about the request to generate a callback for and returns a function.
You can then use an invocation of that function as the callback parameter, like this: callback=buildCallback('something') It will return a script that looks like this:
buildCallback('something')({"message: ... })
This code calls the buildCallback method, then calls the function that the buildCallback method returns.
For example:
(Assuming that each hotel has a <div class="HotelReviews" id="giveThisToYelp">)
function buildCallback(hotelName) {
return function(data) {
$.each(data.businesses, function(i,business){
// extra loop
$.each(business.reviews, function(i,review){
var content = '<p>Review - ' + review.text_excerpt + ' Read more...</p>';
content += 'Rating - <img src="' + business.rating_img_url + '" />';
content += '<p>Date Added - ' + review.date + '</p>';
$(content).appendTo('#' + hotelName);
});
});
};
}
$(function() {
$('.HotelReviews').each(function() {
$.getScript("http://api.yelp.com/business_review_search?"+
"term=" + this.id +
"&location=B26%203QJ"+
"&ywsid=[...]"+
"&callback=buildCallback(" + this.id + ")"
);
});
});
Instead of inserting a script tag on the page with the request url and a callback function name, You should make multiple requests to Yelp services manually.
A simple example in JQuery:
function LoadReviews() {
for (var i = 0; i < myhotels.length; i++) {
$.getJSON("http://api.yelp.com/business_review_search?" + myhotels[i], null, showData);
}
}
Where the myhotels array contains the search parameters for each of your hotels.