i'm currently using Tabletop to make a spreadsheet act like database for my blogspot
<html>
<body>
<p id="demo"></p>
<script src='https://cdnjs.cloudflare.com/ajax/libs/tabletop.js/1.5.1/tabletop.min.js'></script>
<script type='text/javascript'>
var publicSpreadsheetUrl = '1ZXZVfon9ywNelbVEchOu9HQbSLZJRE-x6G2xOFPA-lA';
function init() {
Tabletop.init( { key: publicSpreadsheetUrl,
callback: showInfo,
simpleSheet: true } )
}
function showInfo(data, tabletop) {
alert('Successfully processed!' + data.length + 'rows!')
// console.log(data);
var str = JSON.stringify(data);
document.getElementById("demo").innerHTML = str;
}
document.write("Document <a target='_new' href='" + publicSpreadsheetUrl + "'>Here</a>");
window.addEventListener('DOMContentLoaded', init)
</script>
</body>
</html>
[enter image description here][1]
how to use local variable so i can print outside the function, like this
function showInfo(data, tabletop) {
alert('Successfully processed!' + data.length + 'rows!')
// console.log(data);
var str = JSON.stringify(data);
}
document.getElementById("demo").innerHTML = str;
document.write("Document <a target='_new' href='" + publicSpreadsheetUrl + "'>Here</a>");
window.addEventListener('DOMContentLoaded', init)
</script>
full link
https://docs.google.com/spreadsheets/d/1ZXZVfon9ywNelbVEchOu9HQbSLZJRE-x6G2xOFPA-lA/pubhtml
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/tabletop.js/1.5.1/tabletop.min.js'></script>
<p id="demo"></p>
<script type='text/javascript'>
var publicSpreadsheetUrl = 'https://docs.google.com/spreadsheets/d/1ZXZVfon9ywNelbVEchOu9HQbSLZJRE-x6G2xOFPA-lA/pubhtml';
function init() {
Tabletop.init( { key: publicSpreadsheetUrl,
callback: showInfo,
simpleSheet: true } )
}
function showInfo(data, tabletop) {
var str = JSON.stringify(data);
document.getElementById("demo").innerHTML = str;
}
document.write("Document <a target='_new' href='" + publicSpreadsheetUrl + "'>Here</a>");
window.addEventListener('DOMContentLoaded', init)
</script>
</body>
</html>
Related
I am receiving undefined for the variable called: names
Any help on why it is not displaying the results. It will display in the logger but not on the index.html or the web side after search is pressed.
code:
// var names =[]; //I tried using a global variable but with no luck
function SearchFiles(searchTerm) {
var searchFor = "title contains '" + searchTerm + "'";
var owneris = "and 'Email#email.com' in Owners";
var names = [];
var fileIds = [];
Logger.log(searchFor + " " + owneris);
var files = DriveApp.searchFiles(searchFor + " " + owneris);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId(); // To get FileId of the file
fileIds.push(fileId);
var name = file.getName();
names.push(name);
}
for (var i = 0; i < names.length; i++) {
//this is showing in the Logger
Logger.log(names[i]);
Logger.log("https://drive.google.com/uc?export=download&id=" + fileIds[i]);
}
}
function returnNames(names) {
return '<h3><b>returnNames has ran.!</b></h3> <br>' + names; // Why does this names variable return undefined???
}
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index');
return template.evaluate()
.setTitle('Search Drive')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn)
// shows as undefined in the logger
return resultToReturn;
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm);
google.script.run.processForm(searchTerm);
google.script.run.withSuccessHandler(handleResults).returnNames();
}
function handleResults(searchTerm) {
console.log('Handle Results was called! ');
document.writeln(searchTerm);
}
</script>
</head>
<body>
<input type="text" id="idSrchTerm" name="search">
<input type="button" value="submitButton" name="submitButton" onclick="displayMessage()" />
</body>
</html>
I think you're doing it in the wrong way. It will work if you return returnNames(names) at the end of SearchFiles and you just call google.script.run.withSuccessHandler(handleResults).processForm(searchTerm); inside your index.html like this:
Code.gs
function SearchFiles(searchTerm) {
var searchFor = "title contains '" + searchTerm + "'";
var owneris = "and 'Email#email.com' in Owners";
var names = [];
var fileIds = [];
Logger.log(searchFor + " " + owneris);
//Logger.log(searchFor);
var files = DriveApp.searchFiles(searchFor + " " + owneris);
//var files = DriveApp.searchFiles(searchFor);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId(); // To get FileId of the file
fileIds.push(fileId);
var name = file.getName();
names.push(name);
}
for (var i = 0; i < names.length; i++) {
//this is showing in the Logger
Logger.log(names[i]);
Logger.log("https://drive.google.com/uc?export=download&id=" + fileIds[i]);
}
return returnNames(names); // Here call directly returnNames and get the wanted result
}
function returnNames(names) {
var result = '<h3><b>returnNames has ran.!</b></h3> <br>'; // + names; // Why does this names variable return undefined???
result += '<div>names.length = '+names.length+'</div>';
for(var i=0; i<names.length; i++) {
result += '<div>'+names[i]+'</div>';
}
return result;
}
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index');
return template.evaluate()
.setTitle('Search Drive')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn)
// shows as undefined in the logger
return resultToReturn;
}
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm);
//google.script.run.processForm(searchTerm);
//google.script.run.withSuccessHandler(handleResults).returnNames();
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm);
}
function handleResults(searchTerm) {
console.log('Handle Results was called! ');
document.writeln(searchTerm);
}
</script>
</head>
<body>
<input type="text" id="idSrchTerm" name="search">
<input type="button" value="submitButton" name="submitButton" onclick="displayMessage()" />
</body>
</html>
The result screenshot of my files using the term "test":
You can try it this way to pass around names to your google script.
In SearchFiles(searchTerm) you return names (which can be either blank array or valued array with names in it).
// var names =[]; //I tried using a global variable but with no luck
var Logger = {
log: function(){
console.log(arguments[0]);
}
};
function SearchFiles(searchTerm) {
var searchFor = "title contains '" + searchTerm + "'";
var owneris = "and 'Email#email.com' in Owners";
var names = ["file1","file2","file3"];
var fileIds = [];
Logger.log(searchFor + " " + owneris);
/* var files = DriveApp.searchFiles(searchFor + " " + owneris);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId(); // To get FileId of the file
fileIds.push(fileId);
var name = file.getName();
names.push(name);
}*/
for (var i = 0; i < names.length; i++) {
//this is showing in the Logger
Logger.log(names[i]);
Logger.log("https://drive.google.com/uc?export=download&id=" + fileIds[i]);
}
return names;
}
function returnNames(names) {
return '<h3><b>returnNames has ran.!</b></h3> <br>' + names; // Why does this names variable return undefined???
}
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index');
return template.evaluate()
.setTitle('Search Drive')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn)
// shows as undefined in the logger
return resultToReturn;
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = "DUMMY TEXT";//document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm);
//google.script.run.processForm(searchTerm);
//google.script.run
//.withSuccessHandler(handleResults)
//.returnNames(google.script.run.processForm(searchTerm));
processForm(searchTerm);
}
function handleResults(searchTerm) {
console.log('Handle Results was called! ');
document.writeln(searchTerm);
}
</script>
</head>
<body>
<input type="text" id="idSrchTerm" name="search">
<input type="button" value="submitButton" name="submitButton" onclick="displayMessage()" />
</body>
</html>
I am very close, however not there yet. The logger displays the search results- however I still am not able to get the results to display on the web app.
The search on the web app does work and the results display in the logger.
Please advise. Thanks!
Here is updated,
Code:
function SearchFiles(searchTerm) {
var searchFor ="title contains '" + searchTerm + "'";
var owneris ="and 'Email#email.com' in Owners";
var names =[];
var fileIds=[];
Logger.log(searchFor + " " + owneris);
var files = DriveApp.searchFiles(searchFor + " " + owneris);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
fileIds.push(fileId);
var name = file.getName();
names.push(name);
}
for (var i=0;i<names.length;i++){
//this is showing in the Logger
Logger.log(names[i]);
Logger.log("https://drive.google.com/uc?export=download&id=" + fileIds[i]);
}
}
function returnNames() {
var names = SearchFiles();
return '<b>returnNames has ran.!</b> <br>' + names ;
}
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Index');
return template.evaluate()
.setTitle('Hello World')
// .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn)
// shows as undefined in the logger
return resultToReturn;
}
function helloWorld()
{
return "Hello World!";
}
INDEX:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.processForm(searchTerm);
google.script.run.withSuccessHandler(handleResults).returnNames();
}
function handleResults(returnVal){
console.log('Handle Results was called! ');
document.writeln(returnVal);
}
</script>
</head>
<body>
<input type="text" id="idSrchTerm" name="search">
<input type="button" value="submitButton" name="submitButton" onclick="displayMessage()"/>
</body>
</html>
You are missing the withSuccessHandler of the script runner.
Check out the docs at:
https://developers.google.com/apps-script/guides/html/reference/run#withSuccessHandler(Function)
example:
<script>
google.script.run
.withSuccessHandler(handleResults)
.processForm(searchTerm);
function handleResults(returnVal){
console.log(returnVal)
}
</script>
ok i have my files on apache so i can read it localhost i have one issue cause iam new and i really cant understand how to load xml files with js i see all the topics in stuck overflow and iam stuck .....
i have the main htm file . should i change the path to var indexFile and var xmlFile to my localhost like this var indexFile="file:///C:/Apache24/htdocs/data/index.xml"; ??
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var direction=1;
var titleis="Loading.........";
function showLoading(){
//if (window.status.charAt(0)=="O"){direction=0}
//if (window.status.charAt(titleis.length-1)=="O"){direction=1}
if (direction==0){
window.status=window.status.charAt(titleis.length-1)+window.status.substr(0,titleis.length-1);
}else{
window.status=window.status.substr(1,titleis.length-1)+window.status.charAt(0);
}
}
window.status=titleis;
var timeID=setInterval("showLoading();", 100);
</script>
<script Src="scripts/config.js" language=jscript></script>
<script Src="scripts/general.js" language=jscript></script>
<script Src="inc/header.js" language=jscript></script>
<script src="scripts/grid.js"></script>
<script src="scripts/xml.js"></script>
<SCRIPT LANGUAGE="JavaScript">
// this page should never load inside of another frame
window.onerror = handleError;
var xmlHttp = new Active.XML.Table;
var xmlLoaded=false;
var xmlData;
var indexFile="data/Index.xml";
var xmlIndex =CreateXMLObj(false);
var hasOrders=false;
var idxLoaded=false;
var HtmlIdx;
var xmlFile="data/Catalogue.xml";
var RootTag = "CATALOGUE";
var RecordTag = "PART";
function InitSync()
{
if( "object" == typeof( top.deeptree ) && "unknown" == typeof( top.deeptree.Sync ) )
{
top.deeptree.Sync();
}
}
function SetTitle(name){
_Title = name
document.title =_Title;
}
function SetAsterisc(){
document.title =_Title + '*';
}
function loaddata(){
if (!xmlLoaded) {
if (!xmlHttp.isReady()){
window.status="Φόρτωση δεδομένων...";
xmlHttp.defineProperty("async",false);
xmlHttp.setURL(xmlFile);// provide data URL
xmlHttp.request();// start asyncronous data retrieval
window.status="Done";
}
xmlData=xmlHttp.getXML();
if (xmlHttp.isReady() && !xmlHttp.getAsync()){
xmlLoaded=true;
}else{
xmlLoaded=true;
}
}
return xmlLoaded;
}
function loadIndexes(){
if (!idxLoaded) {
window.status="Φόρτωση δεδομένων...";
if(xmlIndex.load(indexFile)){
idxLoaded=true;
}else{
idxLoaded=false;
alert( 'parseError : ' + xmlIndex.parseError.reason + '\n' +
'Code : ' + xmlIndex.parseError.errorCode + '\n' +
'Line : ' + xmlIndex.parseError.line + '\n' +
'Source : ' + xmlIndex.parseError.srcText + '\n' +
'Pos : ' + xmlIndex.parseError.linepos + '\n' +
'filepos : ' + xmlIndex.parseError.filepos + '\n'
,1,document.title);
}
window.status="Done";
}
return idxLoaded;
}
function strnull(value,_default){
if (value==null || value==""){
return _default;
}
return value;
}
function getNameID(AID){
if(AID<0){return}
return new String(getsafeData(xmlData,"//" + RecordTag + "[AID=" + AID + "]/NameID"));
}
function getPictureNo(AID){
if(AID<0){return}
return new String(getsafeData(xmlData,"//" + RecordTag + "[AID=" + AID + "]/PictureNo"));
}
function getOrder(AID){
if(AID<0){return}
return parseInt(getsafeData(xmlData,"//" + RecordTag + "[AID=" + AID + "]/Order"));
}
function getPicName(PicNo){
return getsafeData(xmlIndex,"//menuItem" + "[#id=" + PicNo + "]/#name");
}
function SetOrder(AID,value){
if(AID<0){return false;}
xmlData.selectSingleNode("//" + RecordTag+ "[AID=" + AID + "]/Order").text=value;
hasOrders=true;
return true;
}
function ClearOrder(AID){
if(AID<0){return false;}
return SetOrder(AID,"");
}
function ClearOrders(){
var StrQuery = "//" + RecordTag + "[Order>0]";
var xmlNodeLst = xmlData.selectNodes(StrQuery);
for(var i=0;i<xmlNodeLst.length;i++){
xmlNodeLst(i).selectSingleNode("Order").text="";
var id=xmlNodeLst(i).selectSingleNode("AID").text;
SetOrder(id,"");
}
hasOrders=false;
return true;
}
function InputOrder(AID){
if(AID>=0){
var oldvalue=getOrder(AID);
if(isNaN(oldvalue)){oldvalue=0};
var value=window.prompt("Εισάγετε ποσότητα για το αντ/κό με Αρ.Ονομαστικου :'" + getNameID(AID) +"'.",oldvalue);
if (value!=null){
if(isNaN(value)){value=0};
if (value!=oldvalue){
if (value > 0) {
SetOrder(AID,value);
return value;
}
}
}
}else{
return null;
}
}
</SCRIPT>
</HEAD>
<SCRIPT ID=clientEventHandlersJS LANGUAGE=javascript>
function window_onbeforeunload() {
if (hasOrders){
window.event.returnValue="\n---------------------------------------------------------------------\nΑν φύγετε από τη σελίδα θα χαθούν οι καταχωρήσεις σας.\n---------------------------------------------------------------------\nΠΑΤΗΣΤΕ OK για να φύγετε.\nΠΑΤΗΣΤΕ CANCEL για να παραμείνετε.\n\n";
}
}
</SCRIPT>
<SCRIPT LANGUAGE=javascript FOR=document EVENT=onreadystatechange>
document_onreadystatechange();
</SCRIPT>
<SCRIPT ID=clientEventHandlersJS LANGUAGE=javascript>
function document_onreadystatechange(){
if (document.readyState == "complete") {
clearInterval(timeID);
//window.showModelessDialog("logo1st.htm",self,'dialogwidth: 558px; DialogHeight:430px;status: no; resizable:no;help:no;maximize:no;minimize:no;');
window.status="Done";
}
}
</SCRIPT>
<SCRIPT LANGUAGE=javascript FOR=window EVENT=onbeforeunload>
window_onbeforeunload();
</SCRIPT>
<!---->
<script language=javascript>
var urlIs=QueryString('url')
if (urlIs==null || urlIs==''){urlIs='logo1st.htm';}
document.write('<FRAMESET name="FrmSet" onload="" rows="36,*" border="1" FRAMESPACING="0" TOPMARGIN="0" LEFTMARGIN="0" MARGINHEIGHT="0" MARGINWIDTH="0">');
document.write('<FRAME name="fraTop" src="top.htm" scrolling="no" border="0" frameborder="no" noresize TOPMARGIN="0" LEFTMARGIN="0" MARGINHEIGHT="0" MARGINWIDTH="0"></FRAME>');
document.write('<FRAMESET name="fstMain" cols="1,*" border="1" frameborder="1" FRAMESPACING="2" TOPMARGIN="0" LEFTMARGIN="0" MARGINHEIGHT="0" MARGINWIDTH="0">');
document.write('<FRAME name="fraLeftFrame" src="Left.htm?frame=true&selection=' + QueryString('selection') + '"scrolling="no" noresize TOPMARGIN="0" LEFTMARGIN="0" MARGINHEIGHT="0" MARGINWIDTH="0" FRAMEBORDER="1" BORDER="1"></FRAME>');
document.write('<FRAME name="fraRightFrame" src="' + urlIs + '?frame=true&hidetoc=false&selection=' + QueryString('selection') + '" FRAMEBORDER="no" BORDER="0" BORDERCOLOR="#b1c3c0"></FRAME>');
document.write('</FRAMESET>');
document.write('</FRAMESET>');
</script>
</HTML>
this code works on IE 5 I THINK BUT not ON latest browsers what i have to change for make it work my xml docs are in apache C:\Apache24\htdocs\data
Hi I want to just add the group ID to the start of the web page, I'm trying to append it to the div "test", and then add a space - allow it to pull data from the yammer API, and then loop through groups with a separation including the group ID. Can anyone tell me why it will print to the webpage in the callback but not outside of the callback? Thanks :)
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
var page = 1;
var groupIDs = [4271656,5896212,1188700];
var n=0;
while (n< groupIDs.length){
$('#test').append("Group ID:" + "WHY WON'T YOU APPEND" + "<br/>");
getYammerJSON(page);
function getData(returnData){
$.each(returnData.users, function(key, value){
if(value.email != undefined){
$('#test').append(value.email + "<br/>");
}
});
}
function getYammerJSON(page){
$.get("https://www.yammer.com/api/v1/users/in_group/" + groupIDs[n] + ".json?page=" + page, function(returnData) {
getData(returnData);
if(!returnData.more_available === true){
return false;
}
else {
page++;
getYammerJSON(page);
}
});
}
n++;
}
</script>
</head>
<body>
<div id="test">User Emails in Yammer Group IDs</div>
</body>
</html>
because your script is not able to find $('#test') div. As you have not put any .ready() event block for document the script gets executed before $('#test') div appears.
So you need to wrap your code inside doc ready block:
$(function(){
var page = 1;
var groupIDs = [4271656,5896212,1188700];
var n=0;
while (n< groupIDs.length){
$('#test').append("Group ID:" + "WHY WON'T YOU APPEND" + "<br/>");
getYammerJSON(page);
function getData(returnData){
$.each(returnData.users, function(key, value){
if(value.email != undefined){
$('#test').append(value.email + "<br/>");
}
});
}
function getYammerJSON(page){
$.get("https://www.yammer.com/api/v1/users/in_group/" + groupIDs[n] + ".json?page=" + page, function(returnData) {
getData(returnData);
if(!returnData.more_available === true){
return false;
}
else {
page++;
getYammerJSON(page);
}
});
}
n++;
}
});
Edits:
You can move your append in here:
function getData(returnData){
$.each(returnData.users, function(key, value){
if(value.email != undefined){
$('#test').append(value.email + "<br/>");
$('#test').append("Group ID:" + "WHY WON'T YOU APPEND" + "<br/>"); // <----move it here.
}
});
}
write your script at the bottom of page or put the test div at the top.
you are running your js code before the tag is even rendered ... it wont find div so it wont append anything
IT NOT SHOULD BE LIKE THIS
<script>
$("#test").append("ghgh");
</script>
<div id = "test"> jj </div>
IT SHOULD BE LIKE THIS
<div id = "test"> jj </div>
<script>
$("#test").append("ghgh");
</script>
EDIT 1:
If you really want to run your code first then append all the text in a string type variable and then at the end just add it the to value of div.
EDIT 2:
Like this
<script>
for( condtion counter etc)
{
str_var+= "your text";
}
</script>
and then after running your srcipt
$("#test").text(str_var); or $("#test").val(str_var); or append
Solutions:
1.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(function(){
var page = 1;
var groupIDs = [4271656,5896212,1188700];
var n=0;
while (n< groupIDs.length){
$('#test').append("Group ID:" + "WHY WON'T YOU APPEND" + "<br/>");
getYammerJSON(page);
function getData(returnData){
$.each(returnData.users, function(key, value){
if(value.email != undefined){
$('#test').append(value.email + "<br/>");
}
});
}
function getYammerJSON(page){
$.get("https://www.yammer.com/api/v1/users/in_group/" + groupIDs[n] + ".json?page=" + page, function(returnData) {
getData(returnData);
if(!returnData.more_available === true){
return false;
}
else {
page++;
getYammerJSON(page);
}
});
}
n++;
}
});
</script>
</head>
<body>
<div id="test">User Emails in Yammer Group IDs</div>
</body>
2.
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="test">User Emails in Yammer Group IDs</div>
<script>
var $ = jQuery;
var page = 1;
var groupIDs = [4271656,5896212,1188700];
var n=0;
while (n< groupIDs.length){
$('#test').append("Group ID:" + "WHY WON'T YOU APPEND" + "<br/>");
getYammerJSON(page);
function getData(returnData){
$.each(returnData.users, function(key, value){
if(value.email != undefined){
$('#test').append(value.email + "<br/>");
}
});
}
function getYammerJSON(page){
$.get("https://www.yammer.com/api/v1/users/in_group/" + groupIDs[n] + ".json?page=" + page, function(returnData) {
getData(returnData);
if(!returnData.more_available === true){
return false;
}
else {
page++;
getYammerJSON(page);
}
});
}
n++;
}
</script>
</body>
</html>
I am trying to grab any xml tag in this sample. But if I try grabbing anything other than the data in the first record in IE I cannot do it. What kind of javascript can I write to correct this?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Get Any XML Tag</title>
<script type='text/javascript' src='http://imaginationeverywhere.info/jslib//dev/jquery-1.5.1.js'>
</script>
<script type="text/ecmascript">
function getData() {
var XMLHTTPRequestObject = false;
if (window.XMLHTTPRequest) {
XMLHTTPRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHTTPRequestObject = new ActiveXObject('Microsoft.XMLHTTP');
}
if (XMLHTTPRequestObject) {
XMLHTTPRequestObject.open('GET', 'http://imaginationeverywhere.info/xml/cd_catalog.xml', true);
XMLHTTPRequestObject.onreadystatechange = function () {
if (XMLHTTPRequestObject.readyState == 4 && XMLHTTPRequestObject.status == 200) {
var xmlDocument = XMLHTTPRequestObject.responseXML;
displayArtist(xmlDocument);
}
}
XMLHTTPRequestObject.send(null);
}
}
function displayArtist(xmldoc) {
titleName = xmldoc.getElementsByTagName('TITLE');
artistName = xmldoc.getElementsByTagName('ARTIST');
countryName = xmldoc.getElementsByTagName('COUNTRY');
companyName = xmldoc.getElementsByTagName('COMPANY');
priceName = xmldoc.getElementsByTagName('PRICE');
yearName = xmldoc.getElementsByTagName('YEAR');
displayTitle = "The name of this song title is " + titleName[0].firstChild.nodeValue + ".";
displayArtist = "The name of the artist is " + artistName[0].firstChild.nodeValue + ".";
displayCountry = "The name of the artist country is " + countryName[0].firstChild.nodeValue + ".";
displayCompany = "The name of the artist company is " + companyName[0].firstChild.nodeValue + ".";
displayPrice = "This song costs $" + priceName[0].firstChild.nodeValue + ".";
displayYear= "The year this song was released " + yearName[0].firstChild.nodeValue + ".";
var target = document.getElementById('targetDiv');
target.innerHTML = displayTitle + "<br/>" + displayArtist + "<br/>" + displayCountry + "<br/>" + displayCompany + "<br/>" + displayPrice + "<br/>" + displayYear;
}
</script>
</head>
<body>
<h3>Get Tag Value</h3>
<form action="#">
<input type="button" value='Get the name of the artist' onclick="getData()" />
</form>
<div id="targetDiv" style="width:300px; height:20px">
</div>
</body>
</html>
I'd suggest using jQuery - it's practically all browser compatible.
Try this:
function getData() {
$.ajax({
url: 'ajax/test.html',
dataType : 'xml',
success: function(data) {
displayArtist(data);
});
}