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);
};
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 a google sheet, maintaining a list of projects, with some scripting running behind it. I have been able to add functionality to click an Add Project button which opens an HTML window for entering the information, and on submit, add a new record to the sheet.
Now I am working on a process to remove a record if the status is changed to Cancelled. What I would like to do is show an html window listing certain details of the project, and give the user a chance to either go back without cancelling the project, or enter some notes as to why it's being cancelled and then continue.
Where I am stuck is populating the html window with the details of the project. I have figured out one way to do it, but I know that this isn't the best way.
Google Script:
function onEdit(e) {
if(e.range.getColumn() == 9 && e.value == "Cancelled" && e.source.getActiveSheet().getName() == "Summary") {
var cancelSheet = ss.getSheetByName(e.source.getActiveSheet().getName());
var cancelRange = cancelSheet.getRange(e.range.getRow(), 1, 1, cancelSheet.getLastColumn());
var cancelRow = cancelRange.getValues();
openCancelDialog(cancelRow);
}
}
function openCancelDialog(x) {
var html = HtmlService
//.createHtmlOutputFromFile('Cancel')
.createHtmlOutput(
'<table><tr><td colspan = \"2\"><b>You are cancelling the following project:</b></td></tr>' +
'<tr><td>Project Name: </td><td>' + x[0][4] + '</td></tr>' +
'<tr><td>Project Number: </td><td>' + x[0][0] + '</td></tr>' +
'<tr><td>Project Category: </td><td>' + x[0][1] + '</td></tr>' +
'<tr><td>Business Owner: </td><td>' + x[0][17] + '</td></tr>' +
'<tr><td>Project Manager: </td><td>' + x[0][18] + '</td></tr>' +
'</table>'
)
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Cancel a Project');
}
This way is writing the html directly in the gs. What I'd like to do is have a separate html page that gets created. That can be done with this method (and is how I'm creating the Add Project dialog elsewhere in the gs):
function openCancelDialog(x) {
var html = HtmlService.createHtmlOutputFromFile('Cancel').setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Cancel a Project');
}
This would be Cancel.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
<!-- Scripting to get my values? -->
</script>
</head>
<body>
<!-- Layout the window
Add a Comments section
Add a button to go back without cancel
Add a button to submit the cancel and update -->
</body>
</html>
But what I haven't figured out is how to pass the array from the openCancelDialog function to the html, so it cab be shown on the page..
I suspect that I need to add scripting to the Cancel.html file to get those values. But is there a way to send that array to the html while it's being created?
Kos's answer gave me some ideas on how I could work it out. That, as well as some additional reading, especially https://www.w3schools.com/js/js_json_intro.asp and the follow up sections, helped me figure this one out.
New js code:
function onEdit(e) {
if(e.range.getColumn() == 9 && e.value == "Cancelled" && e.source.getActiveSheet().getName() == "Summary") {
var cancelSheet = ss.getSheetByName(e.source.getActiveSheet().getName());
var cancelRange = cancelSheet.getRange(e.range.getRow(), 1, 1, cancelSheet.getLastColumn());
var cancelRow = cancelRange.getValues();
//openCancelDialog(cancelRow);
var aSheet = e.source.getActiveSheet().getName();
var column = e.range.getColumn();
var row = e.range.getRow();
Logger.log("Col: " + column + " Row: " + row + " Sheet: " + aSheet);
Logger.log(cancelRow);
}
Logger.log(e);
}
function openCancelDialog(row) {
var ui = SpreadsheetApp.getUi();
// get template
var template = HtmlService.createTemplateFromFile('Cancel');
var myJSON = JSON.stringify(row);
// pass data to template
template.data = myJSON;
// get output html
var html = template.evaluate();
// show modal window
ui.showModalDialog(html, 'Cancel a Project');
}
New HTML:
<!DOCTYPE html>
<html>
<body>
<table>
<tr><td>Number: </td><td id="number"></td></tr>
<tr><td>Name: </td><td id="name"></td></tr>
<tr><td>Category: </td><td id="category"></td></tr>
<tr><td>Business Owner: </td><td id="owner"></td></tr>
<tr><td>Project : </td><td id="manager"></td></tr>
</table>
<script>
var objII = JSON.parse(<?=data?>);
document.getElementById("number").innerHTML = objII[0][0];
document.getElementById("name").innerHTML = objII[0][4];
document.getElementById("category").innerHTML = objII[0][1];
document.getElementById("owner").innerHTML = objII[0][17];
document.getElementById("manager").innerHTML = objII[0][18];
</script>
</body>
</html>
I suspect there may be more elegant ways to do this, and probably even more "correct" ways. But this seems to be working for what I needed it to do, so I figured I'd post it in case someone else was looking.
Thank you
Use HtmlService.createTemplateFromFile:
function openCancelDialog(row)
{
var ui = SpreadsheetApp.getUi();
// get template
var template = HtmlService.createTemplateFromFile('Cancel');
// pass data to template
template.data = {
row: JSON.stringify(row)
};
// get output html
var html = template.evaluate();
// show modal window
ui.showModalDialog(html, 'Cancel a Project');
}
Cancel.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
var row = <?!=data.row?>;
//document.write(row);
</script>
</body>
</html>
Detailed template documentation: https://developers.google.com/apps-script/guides/html/templates
Here's another way to do it. I like to do it this way because I have a lot more control than I do with templates.
This is a script that I did when I was working on an email example script that is contained in a spreadsheet. This script is a little less complicated because it's just for giving the user the option for removing sent emails from the emailsetup page and archiving them on another page. It does it by creating html on the fly and collecting it as a string and then adding it to another page of html. I launch the html at the end of the script as a dialog that allows the users to select which emails to archive by checking checkboxes and clicking on a button called Archive Selected. I found it easier to put my javascript functions together in a standard html file and then run that through HtmlService first and append the string later.
Here's the script:
function archiveSelectedEmails()
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sht=ss.getSheetByName('EmailSetup');
var rng=sht.getDataRange();
var rngA=rng.getValues();
var s='<html><head><script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script></head><body>';
var s='';
for(var i=2;i<rngA.length;i++)
{
var dataA={};
for(var j=0;j<rngA[1].length;j++)
{
dataA[rngA[1][j]]=rngA[i][j];
}
var row=Number(i+1);
s+='<div id="row' + row + '"><input type="checkbox" name="email" value="' + Number(i+1) + '" />' + ' <strong>Row:</strong> ' + Number(i+1) + ' <strong>Name:</strong> ' + dataA.Name + ' <strong>Email:</strong> ' + dataA.Email + ' <strong>Subject:</strong> ' + dataA.Subject + ' <strong>DateSent:</strong> ' + Utilities.formatDate(new Date(dataA.DateSent), 'GMT-6', "M/dd/yyyy HH:mm:ss") + '</div>';
}
s+='<br /><input type="button" value="Exit" onClick="google.script.host.close();" /><input type="button" value="Archive Checked" onClick="getCheckedBoxes(\'email\');" />';
var html=HtmlService.createHtmlOutputFromFile('htmlToBody').setWidth(800).setHeight(250);
html.append(s);
SpreadsheetApp.getUi().showModelessDialog(html, 'Select Emails to Archive');
}
Here's the html file 'htmlToBody':
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var rowsToArchive = [];
for (var i=0; i<checkboxes.length; i++)
{
if (checkboxes[i].checked)
{
rowsToArchive.push(Number(checkboxes[i].value));
}
}
google.script.run
.withSuccessHandler(setResponse)
.archiveSelectedRows(rowsToArchive);
}
function setResponse(a)
{
var s='<br />Rows: ';
for(var i=0;i<a.length;i++)
{
if(i>0)
{
s+=', ';
}
s+=a[i];
var id='#row' + a[i]
$(id).css('display','none');
}
s+='<br />Total: ' + a.length;
google.script.run.displayMessage(s,'Archived Rows')
}
console.log('script here');
</script>
</head>
<body>
I took your project idea and ran with it a little.
These are the google scripts. You'll notice I started with the name of your function.
function openCancelDialog1()
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sht=ss.getSheetByName('Projects');
var rng=sht.getDataRange();
var rngA=rng.getValues();
var s='';
for(var i=1;i<rngA.length;i++)
{
var dataA={};
for(var j=0;j<rngA[0].length;j++)
{
dataA[rngA[0][j]]=rngA[i][j];
}
var row=Number(i+1);
s+='<div id="row' + row + '"><input type="checkbox" name="project" value="' + row + '" />' + ' <strong>Row:</strong> ' + Number(i+1) + ' <strong>Name:</strong> ' + dataA.Name + ' <strong>Project:</strong> ' + dataA.Description + '</div>';
}
s+='<br /><input type="button" value="Exit" onClick="google.script.host.close();" /><input type="button" value="Cancel and Archive Checked" onClick="getCheckedBoxes(\'project\');" />';
var html=HtmlService.createHtmlOutputFromFile('htmlToBody').setWidth(800).setHeight(250);
html.append(s);
SpreadsheetApp.getUi().showModelessDialog(html, 'Select Project to Cancel');
}
function archiveSelectedRows(rows)
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sht=ss.getSheetByName('Projects');
var dest=ss.getSheetByName('ArchivedProjects');
var rng=sht.getDataRange();
var rngA=rng.getValues();
var deleted=[];
for(var i=rngA.length-1;i>1;i--)
{
if(rows.indexOf(i+1)>-1)
{
deleted.push(Number(i+1));
rngA[i][4]=Utilities.formatDate(new Date(), 'GMT-7', 'M/d/yyyy')
dest.appendRow(rngA[i]);
sht.deleteRow(i+1);
}
}
var msg='Row Numbers Deleted = ' + deleted;
var title='Rows Deleted';
var timeout=10;
return deleted;
}
function displayMessage(msg,title)
{
msg+='<br /><input type="button" value="Exit" onClick="google.script.host.close()"; />';
var html=HtmlService.createHtmlOutput(msg).setWidth(400).setHeight(300);
SpreadsheetApp.getUi().showModelessDialog(html, title);
}
This is the htmlTobody file. It's been modified a bit for this situation.
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var rowsToArchive = [];
for (var i=0; i<checkboxes.length; i++)
{
if (checkboxes[i].checked)
{
rowsToArchive.push(Number(checkboxes[i].value));
}
}
google.script.run
.withSuccessHandler(setResponse)
.archiveSelectedRows(rowsToArchive);
}
function setResponse(a)
{
var s='<br />Row Numberss: ';
for(var i=0;i<a.length;i++)
{
if(i>0)
{
s+=', ';
}
s+=a[i];
var id='#row' + a[i]
$(id).css('display','none');
}
s+='<br />Total: ' + a.length;
google.script.run.displayMessage(s,'Canceled Rows')
}
console.log('script here');
</script>
</head>
<body>
And this is what my 'Projects' tab looks like. And I have a Projects tab and an ArchivedProjects tab. When I archive the projects they get copied into the ArchivedProjects sheet.
i'm trying use a Java plugin to print to raw print to a ticket printer from a browser. I've written a test program in HTML and Javascript which is working ok, but now i'm trying to transfer the code to a php script for printing tickets in a bigger app. I'm gettting this kind of error in firefox debug whenever i call a function from the app. "TypeError: qz.findPrinter is not a function".
I changed the extension on the original test program to .php from .html and i'm recieving error there too now.
Any functions from the the java begin with "qz."
Here's the plugin for reference
https://code.google.com/p/jzebra/wiki/TutorialWebApplet
I figure it's something i don't know about php as it works ok as a .html file but I've included the whole script anyway. The php is running from xampp.
Thank you for you time.
<html>
<head><title>Receipt Test</title>
<script type="text/javascript" src="js/deployJava.js"></script>
<script type="text/javascript">
deployQZ();
function deployQZ() {
var attributes = {id: "qz", code:'qz.PrintApplet.class',
archive:'qz-print.jar', width:1, height:1};
var parameters = {jnlp_href: 'qz-print_jnlp.jnlp',
cache_option:'plugin', disable_logging:'false',
initial_focus:'false'};
if (deployJava.versionCheck("1.7+") == true) {}
else if (deployJava.versionCheck("1.6+") == true) {
attributes['archive'] = 'jre6/qz-print.jar';
parameters['jnlp_href'] = 'jre6/qz-print_jnlp.jnlp';
}
deployJava.runApplet(attributes, parameters, '1.5');
}
function countSpace(product, price, section) {
var spaceNeeded = (section - product.length - price.toString().length);
var spaces = "";
for(i=0; i < spaceNeeded; i++) {
spaces += " ";
}
return (product + spaces + price);
}
function findPrinter() {
// Searches for locally installed printer with "zebra" in the name
qz.findPrinter("zebra");
// Hint: Carriage Return = \r, New Line = \n, Escape Double Quotes= \"
var ticketTime = new Date();
var singleLine = "\n------------------------------------------\n";
var doubleLine = "\n==========================================\n";
var product = ["Mirdan Tuzlama", "Suckuklu Pide" ];
var price = [8.00, 8.00];
var prodCharLength = 37;
var finCharLength = 42;
var subTotal = {name:"Subtotal", value:0};
for(i=0;i<product.length;i++) {
subTotal.value += price[i];
}
var tax = {name:"Tax", value:((20/100)*subTotal.value)};
var total = {name:"Total", value:(subTotal.value-tax.value)};
var ticketEnd = " Thank You\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
var productSec = "";
tax.value = 0 - tax.value;
for(j=0;j<product.length;j++) {
var priceloop = price[i];
productSec += (" - 1 " + countSpace(product[j], price[j],prodCharLength));
if (j<=(product.length-2)){
productSec += "\n"
}
}
qz.append("\nDate:" + ticketTime.getDate() + "/"
+ (ticketTime.getMonth()+1) + "/"
+ ticketTime.getFullYear()
+ "\nTime:" + ticketTime.getHours() + ":"
+ ticketTime.getMinutes()
+ "\nTable: B10\nTicket No:2"
//+ singleLine + " - 1 " + product1 +" 8.00\n - 1 " + product1 +" 8:00"
+ singleLine + productSec
+ doubleLine + countSpace(subTotal.name, subTotal.value,finCharLength)
+ '\n' + countSpace(tax.name, tax.value,finCharLength)
+ '\n' + countSpace(total.name, total.value,finCharLength)
+ doubleLine + ticketEnd);
qz.print();
}
</script>
<body>
<input type="button" onClick="findPrinter()" value="Print ESCP" /><br />
</body>
"TypeError: qz.findPrinter is not a function"
In QZ "Tray" 1.9 (desktop Application), qz.findPrinter(...) is defined as a preemptive function, created by qz-websocket.js and must be included in your project to be exposed. If you didn't include qz-websocket.js, this message will occur.
In QZ "Print" 1.9 (Java Applet) and older, qz.findPRinter(...) was exposed through a Java Applet using Java LiveConnect calls, so this was a sign the applet did not load. If your applet did not load properly, this message will occur.
Note: 1.9 was capable of behaving as both a desktop application AND a Java applet.
Deprecation warning: 1.9 and older are EOL. QZ Tray 2.0 and higher, the API has changed significantly. A migration guide is available.
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:
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.