I have a web page with a table which generates once from a XMLHttpRequest. The response includes a JSON with some text and associated links to three attachments that may or may not be there, so I have to loop through those to store variables and create links, like so:
function drawWITable(tableObjArr) {
tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries.reverse();
var tableCount = Object.keys(tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries).length;
var tableHeader = "<table><tr><th class='general'>ФИО</th><th class='general'>Примечания</th><th class='general'>Дата создания</th><th class='general'>Группа</th><th class='attch1'> </th><th class='attch2'> </th><th class='attch3'> </th></tr>";
var tableContent = "";
for(i = 0; i < tableCount; i++) {
tableContent = tableContent + "<tr class='hoverHL'><td>" + tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values.FullName + "</td><td>" + tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Detailed Description"] + "</td><td>" + moment(Date.parse(tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log Submit Date"])).format('dd, MMMM DD YYYY, HH:mm:ss') + "</td><td>" + tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values.DftSupportGroup + "</td>";
if (tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log01"] != null) {
wrklgID = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log ID"];
attachName1 = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log01"].name;
tableContent = tableContent + "<td class='attchentry' onClick='getAttachment1(authToken, wrklgID, attachName1);'>" + "1" + "</td>";
}
if (tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log02"] != null) {
wrklgID = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log ID"];
attachName2 = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log02"].name;
tableContent = tableContent + "<td class='attchentry' onClick='getAttachment2(authToken, wrklgID, attachName2);'>" + "1" + "</td>";
}
if (tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log03"] != null) {
wrklgID = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["Work Log ID"];
attachName3 = tableObjArr[event.currentTarget.querySelector(".entry-cell > #cellCount").innerHTML].entries[i].values["z2AF Work Log03"].name;
tableContent = tableContent + "<td class='attchentry' onClick='getAttachment3(authToken, wrklgID, attachName3);'>" + "1" + "</td>";
}
tableContent = tableContent + "</tr>";
}
var tableFooter = "</table>";
document.getElementById("request-worklog").innerHTML = tableHeader + tableContent + tableFooter;
$("#request-worklog table tbody tr th").resizable({
minHeight: 20,
maxHeight: 20
});
}
Then, by clicking either of the attachment areas user should be able to download file.
function getAttachment1(authToken, wrklgID, attachName1) {
var data = "undefined=";
var request = new XMLHttpRequest();
request.withCredentials = true;
request.open("GET", "http://XXXXXXXXXXXXXXXX/v1/entry/WOI:WorkInfo/" + wrklgID + "/attach/z2AF%20Work%20Log01", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Authorization", authToken);
request.setRequestHeader("Cache-Control", "max-age=0");
request.responseType = "blob";
request.send(data);
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var content = request.response;
console.log(content);
}
};
}
Right now after clicking I only get network response in form of
PNG
IHDRrWؼøsRGB®ÎégAMA±üa pHYsÒÝ~ütIMEÞ,-ËòtEXtSoftwarepaint.net 4.0.9l3~NIDATx^íTÕÙÇMóK5Ý.Ò¤
R-Ö|ES±1*ÁìF£_H+±¤ÇXbÔ¨`OÑÙÙ]vvg]¶²Íóýÿï9çÎ;gª|qÞçù=sË9ï9÷üï©÷ÞÙI)ÕVfçn
©÷½2;ïmÝu
*zÀxU±ßF¦|fÈ(ÍÐÑa¢ÃÒì?F3b¬fä8Í£Æ&hFOb¬9ÈaÌ!±jÆf¤¸fBøÄÉ1-dWMdÄ{Ñe¶kÜÑ1æ
9Ö°Ìö±íTÈû«HóýcÌ#d¨]ÂN<as÷ á ûTðÑoôæ+çÄý0cÌ£/9ÉB>FU`TV[^aì¨o°&2èÂÄ4a"£ÄêÙsUÃ57ªæ_=¬Züj}êiµyÍêþêTÕ×NTlãäDö¢"}§0¼èqÒ|ô~qß=_%äÇbÌ#$âù«j{þÅ?>&àbOÑq{> qå*ã!j¿Á#e(ßpÃ-ª3Wïõô¸ó£ëª¬DØâ¦Ñ7W>1#ý©Mw.üµ>ýÅPß6Õ_?IÊ¡õñ§À*qÆ|=mÁ9¶u¯R-xLµ<ö¸æO?kW`áOñæg¤W(Æ!Yyµª·½]ÎZë®Ià\ö2CõvtÐÚÚÖ½¬çcYâ¨]uªM ]vñ|Ö¬W3ÏÍ+&k
o,Þ L´<ön=rÄsì1#uUWk½½ò\¼TûàyÔ¨¦Õ÷©Þ-[tÒÝ®®ª#5]?ý\Û6BJá6ßû .¤5ÐD*ÁV®ÎèGÓÒr´F1+'NõÏ"5.[.ïZrÉ5éBÞ{FBêÈã¶Òò$¢Ì޴ƧÌTïántmíKÞ»^Dì;Lµüù´Â}?ÖüУ(4sü{AjkÝUEÿüM3Ç
½m\ÎL7©AÓ
!ï{ äë©N·#}ÀBRDô'õHÖæMÓôHSÄ&-Gó»éÖÛuÁòMHúJ.½Á'HúÔp\Z!B¦]C6pmlZCi1WÈõI
BFær*ìì4¡µi!Cíļóå2ÌØS¿I5þr¥ªùÆéªrÖñàkØþ®jZuêÝÜì-Tk³¾/MHZOs3FÊèR¦Ç×êãNÚw"dâÔ³T|Ʊ*¡äW8N3óx
®Oº púbìRâ¢_ì®KfÔBÄoZ}¿´iÓ¢ #Ç©æGÁß±Ð+8÷tâæén¾Dý-ÿyÇ+"!«Ød2û¿\¸é1GH®ðó$"BþÄ;^!fMjÃÍ?òzQC]ù^úÜÌ»koÊ*fÝ%KtáØt)$¦PÙjr/
OÂéÔ-\ìo9%/¿:]Èû1p YyÄ1~·6Æ etc...
As well as this in the console:
Blob {size: 6698, type: "application/octet-stream"}
size: 6698
type: "application/octet-stream"
__proto__: Blob
What should I do next? How to initiate the download process? I am able to get a name of an attachment from the other side, but that's it, no type or anything. Official documentation isn't much of a help either. I am fairly new to JS, so maybe it's something simple that I'm missing?
Thank you!
If you want the browser download a image instead of show it,you need to set a http header Content-Disposition: attachment.
And you should not use xhr,you should jump to link.
To download after getting the content:
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var content = request.response;
_html5Saver(content, 'myfile.png');
}
};
}
function _html5Saver(blob , fileName) {
// to emulate click action
// because we cannot save directly to client's computer due to security constraints
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
document.body.removeChild(a);
}
Use this to view your file
let blob = new Blob([byteArray], {type: contentType});
var blobURL=URL.createObjectURL(blob);
window.open(blobURL);
Related
I am trying to make tabulator to show clickPopup with data that comes with additional http-request. Here is the definition of certain column, which calls cellPopupFormatterVV function:
{title:"WSCReportVolumes", field:"WSCReportVolumes.ErrorShort",
mutator:mutatorNoData,
clickPopup:cellPopupFormatterVV
},
Here is function itself:
var cellPopupFormatterVV = function(e, cell, onRendered){
var cellContent = cell.getData();
var data = handlerCellPopup();
var container = document.createElement("div");
var contents = "<strong style='font-size:1.2em;'>Status details</strong><br/><ul style='padding:0; margin-top:10px; margin-bottom:0;'>";
contents += "<li><strong>Error:</strong> " + data.ErrorShort + "</li>";
contents += "<li><strong>Error Code:</strong> " + data.ErrorCode + "</li>";
contents += "<li><strong>Error Description:</strong> " + data.ErrorLong + "</li>";
contents += "<li><strong>Failed Check:</strong> " + data.FunctionName + "</li>";
contents += "<li><strong>Result:</strong> " + data.ShortMsg + "</li>";
contents += "</ul>";
container.innerHTML = contents;
return container;
};
I'm trying to get data through function handlerCellPopup() which is in separate file "controller_ajax.js":
<script type="text/javascript" src="controller_ajax.js"></script>
The function itself:
function handlerCellPopup() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
let Response = xhttp.response;
return (Response);
};
xhttp.open("GET", "http://localhost:8003/ajax?cellPopup=rov_WSCReportVolumes_Last&computerName=ALAV706", true);
xhttp.responseType = 'json';
xhttp.send();
}
When I do request through browser, it returns exactly what I expect:
[{"ErrorLong":"Free disk space is low","ExecCode":1,"ErrorShort":"Warning","FunctionName":"Check-IsVolumeLowSpace","ErrorCode":201,"ShortMsg":"C:\\"}]
But if I try to click cell in tabulator no popup is shown. I think there is a problem with handlerCellPopup() but no idea how should I change function. Please, help.
I'm trying to get my data from the API into the table.
I've tried loops but it won't work
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { table: "login", limit: 20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table border='1'>"
for (x in myObj) {
txt += "<tr><td>" +myObj[x].name+ "</tr></td>";
}
txt += "</table>"
document.getElementById("myData").innerHTML = txt;
console.log(JSON.parse(this.responseText));
}
};
xmlhttp.open("GET", "https://api.github.com/users", true);
xmlhttp.setRequestHeader("Content-type", "application//x-www-form-urlencoded");
xmlhttp.send("x="+dbParam);
I would like for the table to be filled with the API data
You are closing the <tr> before the <td>:
txt += "<tr><td>" +myObj[x].name+ "</tr></td>";
fix:
txt += "<tr><td>" +myObj[x].name+ "</td></tr>";
Try this:
var obj, dbParam, xmlhttp, myObj, x = 0, objLen, txt = "";
obj = { table: "login", limit: 20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
objLen = myObj.length;
txt += "<table border='1'>";
while (x < objLen) {
txt += "<tr>";
for (let [key, value] of Object.entries(myObj[x])) {
txt += "<td>" + value + "</td>";
}
txt += "</tr>";
x++;
}
txt += "</table>";
document.getElementById("myData").innerHTML = txt;
// console.log(JSON.parse(this.responseText));
}
};
xmlhttp.open("GET", "https://api.github.com/users", true);
xmlhttp.setRequestHeader("Content-type", "application//x-www-form-urlencoded");
xmlhttp.send("x="+dbParam);
<div id="myData"></div>
It shows all the fetched data in the table. One login in one column. You may change the HTML and manipulate as per your need.
Because the API is not returning any key named - name
Hit this URL on browser and see all the keys in response
https://api.github.com/users
I am changing key name to id, you may use any key which is being returned in response:
txt += "<table border='1'>"
for (x in myObj) {
txt += "<tr><td>" +myObj[x].id+ "</td></tr>";
}
txt += "</table>"
First of all,
you can see below, my working program to fetch Data from two different APIs in two different tables.
First table contains the data from an API : {Cycle, Delegated Stack, Share, expected payment}
The second one gets the data from another API to get : {the cycle, paid reward}
https://codepen.io/alexand92162579/pen/arJqmv?editors=1010
The second Code pen is the same thing but I want to merge the two tables according to the value of the cycle:
https://codepen.io/alexand92162579/pen/OGdjLJ?editors=1011
According to what I read online, I need to use Promises. I have tried this multiple times but never succeeded to make it work !
To try it, enter the Key KT19www5fiQNAiqTWrugTVLm9FB3th5DzH54 in the inputbox.
I will make a donation of 30xtz if someone helps me on this one.
// Fonction to fetch the data for every cycle on the first API
// Data Recolted (Cycle, Balance, Share, Expected Reward, Fee, Status)
// Try to merge with the second table according to the value of cycle
// // KT19www5fiQNAiqTWrugTVLm9FB3th5DzH54 */
function calculate2() {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { table: "cycle", limit: 10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
var KT1 = $('#KT1').val();
console.log(KT1);
xmlhttp.onreadystatechange = function() {
Qfee = 0.08;
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table><tr bgcolor=#000000 color=White>"
txt += "<th>Cycle</th>"
txt += "<th>Balance</th>"
txt += "<th>Share</th>"
txt += "<th>Reward</th>"
txt += "<th>Fee</th>"
txt += "<th>Status</th>"
txt += "</tr>"
for (x in myObj) {
cycle = myObj[x].cycle;
balance = myObj[x].balance/1000000;
TotalReward = myObj[x].rewards/1000000;
status = myObj[x].status.status;
stakingBalance = myObj[x].staking_balance/1000000;
Share = balance/stakingBalance*100;
Fee = Share*TotalReward*Qfee/100;
DelegatorReward = Share*TotalReward/100 - Fee;
txt += "<tr>";
txt += "<td width=10% align=center>" + cycle + "</td>";
txt += "<td width=25% align=center>" + Math.round(balance*100)/100 + "</td>";
txt += "<td width=10% align=center>" + Math.round(Share*10)/10 + " %" + "</td>";
txt += "<td width=10% align=center>" + Math.round(DelegatorReward*100)/100 + "</td>";
txt += "<td width=10% align=center>" + Math.round(Qfee*1000)/10 + " %" + "</td>";
txt += "<td width=30% align=left>" + status + "</td>";
txt += "</tr>";
}
txt += "</table>";
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("POST", "https://api6.tzscan.io/v3/delegator_rewards_with_details/" + KT1, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
/*Fonction to fetch the data for every cycle on the second API
// Data Recolted (Cycle, Payment)
// Try to merge with the first table according to the value of cycle
// // KT19www5fiQNAiqTWrugTVLm9FB3th5DzH54*/
function calculate3() {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { table: "cycle", limit: 10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
var KT1 = $('#KT1').val();
//console.log(KT1);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table><tr bgcolor=#000000 color=White>"
//txt += "<th>Block</th>"
txt += "<th>Cycle</th>"
txt += "<th>Paid</th>"
txt += "</tr>"
//If one transaction has been done for the cycle get from the API request 1 then I put the data on the last column of the table
for (var x = 0; x < 30; x++) {
if (KT1 == myObj[x].type.operations[0].destination.tz) {
console.log("Get one");
Block = myObj[x].type.operations[0].op_level;
console.log(Block);
PaiementCycle = Math.round(Block/4096);
PaiementCycle = PaiementCycle - 6;
console.log(PaiementCycle);
Paid = myObj[x].type.operations[0].amount/1000000;
console.log(Paid);
txt += "<tr>";
//txt += "<td width=10% align=center>" + Block + "</td>";
txt += "<td width=10% align=center>" + PaiementCycle + "</td>";
txt += "<td width=25% align=center>" + Paid + "</td>";
txt += "</tr>";
console.log(txt);
} else {
//console.log("Next");
}
}
txt += "</table>";
document.getElementById("demo2").innerHTML = txt;
return txt;
console.log("ici :" + xmlhttp);
}
};
xmlhttp.open("POST", "https://api6.tzscan.io/v3/operations/tz1XynULiFpVVguYbYeopHTkLZFzapvhZQxs?type=Transaction&number=100", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
$(function () {
/*when #tezos input loses focus, as per original question*/
$('#KT1').blur(function () {
calculate3();
calculate2();
console.log(back)
});
$('#KT1').change(function () {
calculate3();
calculate2();
});
$('#KT1').on(function () {
calculate3();
calculate2();
});
$('#KT1').keyup(function () {
calculate3();
calculate2();
});
$('#KT1').keydown(function () {
calculate3();
calculate2();
});
});
</script>
not tested - but i think it might help - i also tried to reduce function sizes for readability ;)
function getAndLogKT1(){
var KT1 = document.querySelector('#KT1')
console.log(KT1 && KT1.textContent)
return KT1 && KT1.textContent
}
function firstApiReadystatechange(){
}
function createTable(){
return document.createElement('table');
}
function addTableHeader(table, keys){
var thead = document.createElement('thead');
var tr = document.createElement('tr');
for(var i = 0; i < keys.length; i++){
var th = document.createElement('th')
var text = document.createTextNode(keys[i])
th.appendChild(text)
tr.appendChild(th)
}
thead.appendChild(tr)
table.appendChild(thead)
}
function addRowToTableBody(table, rowItems){
var body = table.querySelector('tbody')
if(!body){
body = document.createElement('tbody')
table.appendChild(body)
}
var tr = document.createElement('tr')
for(var i = 0; i < rowItems.length; i++){
var td = document.createElement('td')
var text = document.createTextNode(rowItems[i])
td.appendChild(text)
tr.appendChild(td)
}
body.appendChild(tr)
}
function getDbParam(dbParmaObj){
return JSON.stringify(dbParmaObj)
}
function sendRequestFirstApi(xmlhttp, KT1, dbParam){
xmlhttp.open("POST", "https://api6.tzscan.io/v3/delegator_rewards_with_details/" + KT1, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
function fetchDataForEveryCycleOnFirstApi(){
return new Promise((resolve, reject) => {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
var Qfee = 0.08;
if(this.readyState === 4 && this.status === 200){
try {
var responseObj = JSON.parse(this.responseText)
resolve(responseObj)
} catch {
reject({err: "json parse error"})
}
}
}
sendRequestFirstApi(xmlhttp, getAndLogKT1(), getDbParam({table: "cycle", limit: 10}))
})
}
function sendRequestSecondApi(xmlhttp, dbParam){
xmlhttp.open("POST", "https://api6.tzscan.io/v3/operations/tz1XynULiFpVVguYbYeopHTkLZFzapvhZQxs?type=Transaction&number=100", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
function fetchDataForEveryCycleOnSecondApi(){
return new Promise((resolve, reject) => {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
var Qfee = 0.08;
if(this.readyState === 4 && this.status === 200){
try {
var responseObj = JSON.parse(this.responseText)
resolve(responseObj)
} catch {
reject({err: "json parse error"})
}
}
}
sendRequestSecondApi(xmlhttp, getDbParam({table: "cycle", limit: 10}))
})
}
function parseObjectCycleHashed(respObject){
var retObj = {}
for(var x in respObject){
retObj[respObject[x]['cycle']] = respObject[x]
}
return retObj
}
function mergeCycleHashedResponseObjects(a,b){
let cyclesA = Object.keys(a)
var retObj = Object.assign({}, b)
for(var i = 0; i < cyclesA.length; i++){
Object.assign(retObj, {[cyclesA[i]]: a[cyclesA[i]] })
}
return retObj
}
function addToDOM(element, querySelector){
var el = document.querySelector(querySelector)
el && el.appendChild(element)
}
async function main(){
var responseObjApiOne = await fetchDataForEveryCycleOnFirstApi();
var responseObjApiTwo = await fetchDataForEveryCycleOnSecondApi();
var responseObjApiOneCycleBased = parseObjectCycleHashed(responseObjApiOne);
var responseObjApiTowCycleBased = parseObjectCycleHashed(responseObjApiTwo);
var mergedObject = mergeCycleHashedResponseObjects(responseObjApiOneCycleBased, responseObjApiTowCycleBased)
var table = createTable()
const headerKeys = [
"Cycle",
"Balance",
"Share",
"Reward",
"Fee",
"Status",
"Paid"
]
addTableHeader(table, headerKeys)
for(var cycle in mergedObject){
addRowToTableBody(table, headerKeys.map(columnTitle => {
return mergedObject[cycle][columnTitle]
}))
}
addToDOM(table, "dmeo2")
}
I have a dynamic web project and in this one I try to display elements from a mysql database on an AWS Instance.
So, in my database, I have many elements (name, city, imageURL) and the imageURL is an URL from an image in an amazon S3.
In my html code, if I put the URL directly, the image is displayed but if I get back the URL from the mysql database (with a javascript function), I got the right url with console.log(imageURL) but the image is not displayed and I have this error :
GET https://s3-us-west-2.amazonaws.com/.... 403 (Forbidden)
So do you know why this doesn't work ?
EDIT : This is my javascript code :
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "rest/restaurants", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var name;
var id;
var imageURL;
var htmlText = "";
for (i = 0; i< xmlDoc.getElementsByTagName("id").length; i++){
name = xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue;
id = xmlDoc.getElementsByTagName("id")[i].childNodes[0].nodeValue;
imageURL = xmlDoc.getElementsByTagName("imageURL")[i].childNodes[0].nodeValue;
console.log(imageURL);
htmlText = htmlText +
"<div class=\"Popular-Restaurants-grid\">" +
"<div class=\"col-md-3 restaurent-logo\">" +
"<img src="+ imageURL + "class=\"img-responsive\"/>"+
"</div>"+
"<div class=\"col-md-2 restaurent-title\">"+
"<div class=\"logo-title\">"+
"<h4 id=\"test\">" + name + "</h4>"+
"</div>"+
"</div>"
}
document.getElementById("restaurantsContainer").innerHTML = htmlText;
}
Your current code generates a URL like:
<img src=https://s3-us-west-2.amazonaws.com/someText/text/logo1.jpgclass="img-responsive"/>
Add a space to this line:
"<img src="+ imageURL + "class=\"img-responsive\"/>"
to look like:
"<img src="+ imageURL + " class=\"img-responsive\"/>"
Notice the space before the word "class".
This is the function I use
function displayXML(string) {
var i;
var xmlDoc = $.parseXML(string);
var xml = $(xmlDoc);
var table = "<tr><th>Author</th><th>Title</th><th>Genre</th><th>Price</th><th>Publish Date</th><th>Description</th></tr>";
var x = xml.find('book').size();
for ( i = 0; i < x; i++) {
table += "<tr><td>" +
xml[i].getElementsByTagName('author')[0].childNodes[0].nodeValue +
"</td><td>" +
xml[i].getElementsByTagName('title')[0].childNodes[0].nodeValue +
"</td><td>" +
xml[i].getElementsByTagName('genre')[0].childNodes[0].nodeValue +
"</td><td>" +
xml[i].getElementsByTagName('price')[0].childNodes[0].nodeValue +
"</td><td>" +
xml[i].getElementsByTagName('publish_date')[0].childNodes[0].nodeValue +
"</td><td>" +
xml[i].getElementsByTagName('description')[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("showResults").innerHTML = table;
}
Thing is , I can successfully display this string coming from php
<?xml version="1.0" encoding="UTF-8"?><catalog> <book id="1"> <author>KAPIOS</author> <title>KATI0</title> <genre>KATI GENRE</genre> <price>50</price> <publish_date>2000-01-05</publish_date> <description>AXAM</description> </book></catalog>
but I cant do the same for lines that contain 2 or more books
<?xml version="1.0" encoding="UTF-8"?><catalog> <book id="9"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description> </book> <book id="10"> <author>Corets, Eva</author> <title>Maeve Ascendant</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-11-17</publish_date> <description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.</description> </book></catalog>
Also here is the error message
"Uncaught TypeError: Cannot read property 'getElementsByTagName' of undefineddisplayXML"
It just seems strange to me than using getElementsByTag is possible on one case but unusable in another.
Function used to "extract" (I'm generating it via a php call) the xml,this one is working
function getBook() {
clearResults();
var request = new XMLHttpRequest();
var url = "resources/getBooksByTitle.php";
var dataToSent = "dataToSent=" + document.getElementById("booksDropDown").value;
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
displayXML(return_data);
}
}
request.send(dataToSent);
document.getElementById("showResults").innerHTML = "processing...";
}
Second function which doesn't work
function searchBook() {
clearResults();
var request = new XMLHttpRequest();
var url = "resources/getBooksByKeyword.php";
var dataToSent = "dataToSent=" + document.getElementById("searchBox").value;
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
displayXML(return_data);
}
}
request.send(dataToSent);
document.getElementById("showResults").innerHTML = "processing...";
}
function displayXML(string) {
var i;
var xmlDoc = $.parseXML(string);
var xml = $(xmlDoc);
var table = "<tr><th>Author</th><th>Title</th><th>Genre</th><th>Price</th><th>Publish Date</th><th>Description</th></tr>";
var x = xml.find('book').length;
for ( i = 0; i < x; i++) {
table += "<tr><td>" +
xml.find('book')[i].getElementsByTagName('author')[0].childNodes[0].nodeValue +
"</td><td>" +
xml.find('book')[i].getElementsByTagName('title')[0].childNodes[0].nodeValue +
"</td><td>" +
xml.find('book')[i].getElementsByTagName('genre')[0].childNodes[0].nodeValue +
"</td><td>" +
xml.find('book')[i].getElementsByTagName('price')[0].childNodes[0].nodeValue +
"</td><td>" +
xml.find('book')[i].getElementsByTagName('publish_date')[0].childNodes[0].nodeValue +
"</td><td>" +
xml.find('book')[i].getElementsByTagName('description')[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("showResults").innerHTML = table;
}
The xml object itself is not an array, so you extract data from 1 book only(size of a non-array is always 1). Use this one instead.