How to get JavaScript variable from MySQL database table? - javascript

I want to take a JavaScript var from database to JavaScript code.
I have a twitch community that help stream by the way I need to let the user or member add their twitch name to the list so that other members can see them when they are online.
my code is :
JAVASCRIPT
var hello = "hello";
/* This is an alternate method to creating javascript methods
function streamer(name, status, url) {
this.name = name;
this.status = status;
this.url = url;
} */
// The streamer object
// here we will store the necessary information from
// the twitch api json file
var Streamer = {
id: 0,
status: "title",
name: "strimmah",
display_name: "Strimmah",
url: "https://secure.twitch.tv/freecodecamp", // test url
previewImgs: ["large", "medium", "small", "template"],
game: "GaM3",
viewers: 0,
init: function(name, status, game, url) {
this.name = name;
this.status = status;
this.game = game;
this.url = url;
},
init: function(name, status, game, viewers, url) {
this.name = name;
this.status = status;
this.game = game;
this.viewers = viewers;
this.url = url;
},
initPreviewImgs: function(large, medium, small, template) {
this.previewImgs[0] = large;
this.previewImgs[1] = medium;
this.previewImgs[2] = small;
this.previewImgs[3] = template;
}
};
// delete test variables
var test = Object.create(Streamer);
var backUpImage = "https://static-cdn.jtvnw.net/ttv-static/404_preview-640x360.jpg";
var tempStreamers = [
"nokss68",
"snake606",
"team_itxx_cod",
"relapsegtv",
"sokkaenpyjama",
"elfepurpl3",
"lighthund",
"spacecakezed",
"nagatsu6",
"xng360",
"nazenko",
"giiskaa",
"floki_live",
"kayakox",
"jejen64",
"spivix",
"keryg4n",
"mehdii95150",
"mrgeekyfr",
"zaykerz92",
"etsalutdit",
"x_dyn_x",
"martind32",
"el_fideo11",
"xmisticoxx",
"zookervinc78",
"MrCraaftt",
"killerelite84",
"Aqu0ss",
"panteleimon42",
"veynstream",
"le_salty_gamer"
];
var streamDisplayStatus = 1; // 0-ALL, 1-Online Only, 2-Offline only
var twitchURL = "https://secure.twitch.tv/"; // to create channel urls
var streamerArray = [];
var showOffline = true;
// ENTRY POINT,
$(document).ready(function() {
/*for (var i = 0; i < tempStreamers.length; i++) {
loadStreamJsonInfo(tempStreamers[i], test);
}*/
// initial set of streamers, we start with Overview so show all
instantiateStreamers();
// navigator button setup
navigationButtons();
});
function instantiateStreamers() {
streamerArray.length = 0;
for (var i = 0; i < tempStreamers.length; i++) {
var streamer = Object.create(Streamer);
loadStreamJsonInfo(tempStreamers[i], streamer);
}
}
function loadStreamJsonInfo(name, data) {
/*$.getJSON('https://api.twitch.tv/kraken/streams/freecodecamp?callback=?', function(json) {
console.log(json);
}); */
$.getJSON('https://api.twitch.tv/kraken/streams/' + name + '?callback=?',
function(json) {
// console.log(json);
var stream = json.stream;
if (stream !== null) {
var channel = json.stream.channel;
data.init(channel.display_name, channel.status, channel.game, stream.viewers, channel.url);
data.initPreviewImgs(stream.preview.large, stream.preview.medium, stream.preview.small, stream.preview.template);
// console.log(data.name + " " + data.status + " " + data.viewers);
} else {
data.init(name, "Offline", "", 0, twitchURL + name)
data.initPreviewImgs(backUpImage, backUpImage, backUpImage, backUpImage);
}
streamerArray.push(data);
//console.log("TEST: " + streamerArray.length);
checkDisplayStatus(data);
}); // end of getJson
}
function checkDisplayStatus(data) {
switch (streamDisplayStatus) {
case 0:
createStreamerDOMItem(data);
break;
case 1:
if (data.status !== "Offline") {
createStreamerDOMItem(data);
}
break;
case 2:
if (data.status === "Offline") {
createStreamerDOMItem(data);
}
break;
default:
createStreamerDOMItem(data);
console.log("Default switch");
break;
}
}
function createStreamerDOMItem(streamData) {
var divStart = '<div class="streamer-container">';
var divEnd = '</div></div>';
var divStreamerItem = '<div class="streamer-item" align="center">' + '<a target="_blank" href="' + streamData.url +
'"><iframe src="https://player.twitch.tv/?channel='+ streamData.name +'\" frameborder="0" scrolling="no" height="350" width="100%" /></a>' +
'<p id="viewer-count"><font color="yellow">' + streamData.viewers + ' personne(s) sur ' +
'</font>' + streamData.name + '</p>'
+ '';
var final = divStart + divStreamerItem + divEnd;
$(final).appendTo(".live-channels-container");
}
function clearStreamerDOMItems() {
$("div").remove(".streamer-container");
}
HTML
<div>
<div class="navbar-container" >
</div>
<br>
<div class="live-channels-container">
</div>
<!-- END OF STREAMER BOXES-->
</div>
Now I want to get ( var tempStreamers = ) username from DATABASE.

You can get the tempStreamers by JSONP method which you need a new api to output the data.
Use setinterval to run you function every 2 seconds.Then you will get the newest data.

Related

LinkedIn Works with LinkedIn's testDevCo not with wanted company page

I have a problem fetching company updates, but my code works fine with the
following Linkedin testDevCo "var cpnyID = 2414183; //LinkedIn's testDevCo
So My question is that I am an admin to the company that I want to fetch
the updates i from, but why do I get the following error ?
{
"errorCode": 0,
"message": "Unknown authentication scheme",
"requestId": "MRJ33C5FVX",
"status": 401,
"timestamp": 1540989274268
}
Code:
<script type="text/javascript" src="https://platform.linkedin.com/in.js">
api_key: 8616po0krrhh2k
onLoad: onLinkedInLoad, onLinkedInAuth
</script>
<div id="displayUpdates"></div>
<script type="text/javascript">
function onLinkedInLoad() {
IN.Event.on(IN, "auth", onLinkedInAuth);
console.log("On auth");
}
function onLinkedInAuth() {
var cpnyID = 86104; //the Company ID for which we want updates
IN.API.Raw("/companies/" + cpnyID + "/updates?event-type=status-update&start=0&count=3&format=json").method("Get").result(displayCompanyUpdates)
console.log("After auth");
}
function displayCompanyUpdates(result) {
var div = document.getElementById("displayUpdates");
var el = "<ul>";
var resValues = result.values;
for (var i in resValues) {
var share = resValues[i].updateContent.companyStatusUpdate.share;
var isContent = share.content;
var isTitled = isContent,
isLinked = isContent,
isDescription = isContent,
isThumbnail = isContent,
isComment = isContent;
if (isTitled) {
var title = isContent.title;
} else {
var title = "News headline";
}
var comment = share.comment;
if (isLinked) {
var link = isContent.shortenedUrl;
} else {
var link = "#";
}
if (isDescription) {
var description = isContent.description;
} else {
var description = "No description";
}
/*
if (isThumbnailz) {
var thumbnailUrl = isContent.thumbnailUrl;
} else {
var thumbnailUrl = "http://placehold.it/60x60";
}
*/
if (share) {
var content = "<a target='_blank' href=" + link + ">" + comment + "</a><br>";
//el += "<li><img src='" + thumbnailUrl + "' alt=''>" + content + "</li>";
el += "<li><div>" + content + "</div></li>";
}
console.log(share);
}
el += "</ul>";
document.getElementById("displayUpdates").innerHTML = el;
}
</script>
Premission:(r_basicprofile, r_emailaddress, rw_company_admin, w_share)
I am an admin, I can see the company under the "MANAGE" section. But I don't
have the company as my current position in my profile.
"check if you are sending the right request" => how do I do it ?
couple of things you can do/check:
show us your code
show us your application permissions
check if you are an administrator of the company page and the application
check if you have the correct companyID
check if you are sending the right request.

data = JSON.parse(data); syntax error unexpected end of input

I have a problem with my page. It works on localhost (WebServ). On my vps (Debian 8) it not work.
You can look: http://www.csgobeton.pl/withdraw.
When you do recaptcha it says "syntax error unexpected end of input".
In the console I can see there is a problem at line "data = JSON.parse(data);".
Please help me.
function loadLeft(opts) {
inlineAlert("", "Loading your inventory - please wait...");
var DIV = "<div class='placeholder matched' data-name='{0}' data-pos='{1}'
data - price = '{2}'
data - bot = '{3}' > ";
DIV += "<div class='slot {13}' data-view='{15}' data-name='{4}' data-
pos = '{5}'
data - price = '{6}'
data - bot = '{7}'
data - id = '{8}'
style = 'background-
image: url(\"{9}\")'>"; DIV += "<div class='name'>{10}</div>"; DIV +=
"<div class='price {11}'>{12}</div>"; DIV +=
"<div class='bot'>{14}</div>"; DIV += "</div></div>";
var IMG = "{0}/{1}fx{2}f";
var url = "";
if (DEPOSIT) {
url = "/get_inv?" + opts;
} else {
var g = grecaptcha.getResponse();
url = "http://www.csgobeton.pl/get_bank_safe?g-recaptcha-response=" + g;
}
$.ajax({
url: url,
success: function (data) {
$("#inlineAlert").html("data");
try {
data = JSON.parse(data);
if (data.success) {
console.log(data);
$("#left .reals").empty();
$("#right .reals").empty();
$("#right .bricks").removeClass("hidden");
$("#avail").html(formatNum(data.balance));
var count = data.items.length;
var eleA = [];
for (var i = 0; i < count; i++) {
var item = data.items[i];
var url = IMG.format(item.img, 110, 50);
var price_class = "ball-1";
if (DEPOSIT) {
price_class = "ball-0";
}
var slot_class = "";
var price_content = item.price;
if (price_content == 0) {
price_content = item.reject;
slot_class = "reject";
} else {
price_content = formatNum(price_content);
}
bot = 0;
if (item.botid) {
bot = item.botid;
}
var botLabel = "";
if (!DEPOSIT) {
botLabel = "Bot " + bot;
}
var ele = DIV.format(item.name, i, item.price, bot,
item.name, i, item.price, bot, item.assetid, url, item.name,
price_class,
price_content, slot_class, botLabel, item.view);
eleA.push(ele);
}
$("#left_number").html(count);
document.getElementById("left").getElementsByClassName(
"reals")[0].innerHTML = eleA.join('');
addPadding("#left", 6);
if (data.fromcache) {
inlineAlert("success", "Loaded " + count + " items from
cache - < a href = \
"javascript:loadLeft('nocache')\">reload inventory</a>"
);
} else {
inlineAlert("success", "Loaded " + count + " items.");
}
} else {
inlineAlert("error", data.error);
if (data.count > 0) {
cmd();
}
}
if (data.tid) {
showPending(data);
}
} catch (err) {
inlineAlert("error", "Javascript error22: " + err);
console.log(err.stack);
}
},
error: function (err) {
inlineAlert("error", "AJAX error: " + err.statusText);
},
});
}
index.php is:
case 'get_bank_safe':
if(!$user) exit(json_encode(array('success'=>false, 'error'=>'You must
login to access the widthdraw.')));
$g = curl('https://www.google.com/recaptcha/api/siteverify?secret=6Le-
6R8TAAAAAAjgt_wfQMOUCMxCCAWs-iFlP9T-&response='.$_GET['g-recaptcha-response']);
$g = json_decode($g, true);
if($g['success'] == true) {
$array =array('balance'=>$user['balance'],'error'=>'none','items'=>array(),'success'=>true);
mysql_query('SET CHARACTER SET utf8');
$sql = $db->query('SELECT * FROM `items` WHERE `status` = 1');
$prices = file_get_contents('prices.txt');
$prices = json_decode($prices, true);
while ($row = $sql->fetch()) {
$array['items'][] =
array('botid'=>$row['botid'],'img'=>'http://steamcommunity-a.akamaihd.net/economy/image/'.$row['img'],'name'=>$row['market_hash_name'],'ass
etid'=>$row['id'],'price'=>$prices['response']['items']
[$row['market_hash_name']]['value']*10,'reject'=>'unknown items');
}
exit(json_encode($array));
}
break;
The result of get_safe_bank is:
{"balance":"0","error":"none","items": [{"botid":"1","img":"http:\/\/steamcommunity-a.akamaihd.net\/economy\/image\/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFAuhqSaKWtEu43mxtbbk6b1a77Twm4Iu8Yl3bCU9Imii1Xt80M5MmD7JZjVLFH-6VnQJQ","name":"Chroma 2 Case","assetid":"8","price":0,"reject":"unknown items"},{"botid":"1","img":"http:\/\/steamcommunity-a.akamaihd.net\/economy\/image\/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpoo6m1FBRp3_bGcjhQ09ulq5WYh8jiPLfFl2xU18h0juDU-MKljgLjqRVuaj-gLIKUdQdtMgvS-VK_wrvpgZ7quM_Im3Qw6Cdz4CzZgVXp1o7eGVz_","name":"USP-S | Lead Conduit (Well-Worn)","assetid":"26","price":0,"reject":"unknown items"}],"success":true}{"balance":"0","error":"none","items":[{"botid":"1","img":"http:\/\/steamcommunity-a.akamaihd.net\/economy\/image\/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFAuhqSaKWtEu43mxtbbk6b1a77Twm4Iu8Yl3bCU9Imii1Xt80M5MmD7JZjVLFH-6VnQJQ","name":"Chroma 2 Case","assetid":"8","price":0,"reject":"unknown items"},{"botid":"1","img":"http:\/\/steamcommunity-a.akamaihd.net\/economy\/image\/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpoo6m1FBRp3_bGcjhQ09ulq5WYh8jiPLfFl2xU18h0juDU-MKljgLjqRVuaj-gLIKUdQdtMgvS-VK_wrvpgZ7quM_Im3Qw6Cdz4CzZgVXp1o7eGVz_","name":"USP-S | Lead Conduit (Well-Worn)","assetid":"26","price":0,"reject":"unknown items"}],"success":true}
When I paste it instead data = JSON.parse(data); data it works correctly.

How to refresh a div to load new record when theres new record in Database

I have a div in a page where I show a list of records which are stored in my Database ( firebase). Whenever there is a new record in the database, I want the div to auto load in the new record without refreshing the whole page. So how can I do that?
Javascript code on showing records
query.on("child_added", function(messageSnapshot) {
var keys = Object.keys(messageSnapshot);
var messageData = messageSnapshot.val();
var key = messageSnapshot.getKey();
console.log("key is " + messageSnapshot.getKey());
console.log("messagesnapshot is " + messageSnapshot);
var obj = {
key: key,
};
arr.push(obj);
ref.child(key + "/User Information").once('value').then(function(snapshot) {
var name = snapshot.val().firstName
s = "<li><a href='#'>" + no + '. ' + name + ' ' + key + "</a></li>";
no++;
sources.push(s);
// for ( property in messageSnapshot) {
// console.log( property ); // Outputs: foo, fiz or fiz, foo
//}
console.log("arr.length is " + arr.length);
}).then(function(pagination) {
Pagination();
});
});
function Pagination() {
var arrLength = arr.length;
var container = $("#mylist");
// var sources = function () {
// var result = [];
//
// for (var i = 1; i < arrLength; i++) {
// result.push(i);
// }
//
// return result;
// }();
var options = {
dataSource: sources,
pageSize: 10,
callback: function(data, pagination) {
//window.console && console.log(response, pagination);
var dataHtml = '';
$.each(data, function(index, item) {
dataHtml += item;
});
console.log(dataHtml);
container.prev().html(dataHtml);
}
};
//$.pagination(container, options);
container.addHook('beforeInit', function() {
window.console && console.log('beforeInit...');
});
container.pagination(options);
container.addHook('beforePageOnClick', function() {
window.console && console.log('beforePageOnClick...');
//return false
});
return container;
}
Html code div
<div data-role="page" id="pageone">
<div data-role="header">
<button onclick="goBack()">Back</button>
<h1>Pending Transaction</h1>
</div>
<div id="mylist"></div>
</div>
At first your local code must be aware of changes in the Database, so the plain answer is:
Your JS-Code must periodically ask your DB for changes, if changes are available you can call that changes and update your content via an AJAX-Request and put it into the div#mylist
This "periodically ask" is called long polling, aspnet has for example the framework called SignalR

Javascript path to AWS bucket 0 using jPlayer?

I have two blocks of code. They both work together to list and play MP3 files from my AWS S3 Container bucket. But I cannot figure out the path to the "Album Cover" (i.e. Poster). KEEP IN MIND, each album folder contains a poster image that is the same name as the folder with a jpg extension. For example, see below:
Folder name: Beatles-Greatest-Hits
Folder Contents:
song01.mp3
song02.mp3
song03.mp3
Beatles-Greatest-Hits.jpg
This blocks works fine connects to the bucket: II realize it is long, but I am trying the find the path to the poster, so I included it all.
<script type="text/javascript">
var AWS_AccessKeyId = 'MY-KEY-HERE';
var AWS_SecretAccessKey = 'MY-SECRET-HERE';
var AWS_Region = 'REGION-HERE';
var AWS_BucketName = 'musicpax';
var AWS_MaxKeys = 500;
var AWS_Prefix = 'mpx_music/';
var AWS_SignedUrl_Expires = 900;
</script>
<!-- ***** ///////////////////////// ***** -->
<!-- ***** AWS DISPLAY & LIST SCRIPT ***** -->
<!-- ***** ///////////////////////// ***** -->
<script type="text/javascript">
AWS.config.update({accessKeyId: AWS_AccessKeyId, secretAccessKey: AWS_SecretAccessKey});
AWS.config.region = AWS_Region;
var bucket = new AWS.S3({params: {Bucket: AWS_BucketName}});
function listMoreObjects(marker, prefix, countFiles, countFolders) {
$('#overlay').show();
$('#status').html('<div id="statusimg"></div>Loading...');
bucket.listObjects({MaxKeys: AWS_MaxKeys, Marker: marker, Prefix : prefix, Delimiter : '/' },function (err, data) {
if (err) {
$('#status').html('<img src="img/exclamation-red.png"> Could not load objects from S3');
} else {
var truncated = data.IsTruncated;
var nextMarker = data.NextMarker;
$('#moreobjects').remove();
renderObjects(data.Contents, countFolders, countFiles, prefix, truncated, nextMarker);
}
$('#overlay').hide();
});
};
function listObjects(prefix) {
$('#overlay').show();
$('#status').html('<div id="statusimg"></div>Loading...');
$('#objects').empty();
bucket.listObjects({MaxKeys: AWS_MaxKeys, Prefix : prefix, Delimiter : '/' },function (err, data) {
if (err) {
$('#status').html('<img src="img/exclamation-red.png"> Could not load objects from S3');
} else {
//Load folders...
//Set breadcrumbs..
var truncated = data.IsTruncated;
var nextMarker = data.NextMarker;
var currentFolder = '<span class="path">root</span>';
var icon = '';
if (prefix !== '') {
currentFolder += '/';
var folders = prefix.split('/');
var parent = '';
var slash = '';
var topFolder = '';
for (var i = 0; i < folders.length - 1; i++) {
if (folders[i] !== '') {
var path = '';
parent += slash + folders[i];
if ( i > 0 ) {
path = parent;
} else {
path = folders[i];
}
if ( i !== (folders.length - 2)) {
topFolder = path;
}
currentFolder += slash + '<span class="path">' + folders[i] + '</span>';
slash = '/';
}
}
}
if (typeof topFolder != 'undefined') {
if (topFolder !== '') {
topFolder += '/';
}
icon = '<img src="img/arrow-090.png"/>'
// $('#objects').append('<li>' + icon + '<span>...</span></li>');
$('#objects').append('<li>' + '<span>...</span></li>');
}
$('#breadcrumb').html('Current folder is : ' + currentFolder);
//Set folders...
var countFolders = 0;
for (var i = 0; i < data.CommonPrefixes.length; i++) {
var currentPrefix = data.CommonPrefixes[i].Prefix;
var name = (currentPrefix.replace(prefix, '')).replace('/','');
icon = '<img src="img/folder-horizontal.png"/>'
if (prefix !== currentPrefix) {
countFolders++;
// $('#objects').append('<li style="list-style:none;margin-left:-40px;border:1px solid #00f;">' + icon + '<span>' + name + '</span></li>');
$('#objects').append('<li style="list-style:none;padding: 5px 0;margin-left:-40px;border:1px solid #00f;">' + '<span>' + name + '</span></li>');
}
}
renderObjects(data.Contents, countFolders, 0, prefix, truncated, nextMarker);
}
//$('#overlay').hide();
});
};
function renderObjects(contents, countFolders, currentCountFiles, prefix, truncated, nextMarker) {
//Load files...
var countFiles = currentCountFiles;
for (var i = 0; i < contents.length; i++) {
var key = contents[i].Key;
var size = Math.ceil(contents[i].Size / 1024);
var fileName = key.replace(prefix, '');
// icon = '<img src="img/document.png"/>'
if (prefix !== key) {
countFiles++;
var params = {Bucket: 'bucket', Key: 'key'};
$('#objects').append('<li style="list-style:none;">' + icon + '<span>' + fileName + '</span></li>');
}
}
if (truncated) {
$('#status').html('Loaded : ' + countFolders + ' folder(s), showing ' + countFiles + ' item(s) from S3, <img src="img/arrow-270.png">Go to the bottom of the list to load more items.');
// icon = '<img src="img/plus-circle.png"/>'
$('#objects').append('<li id="moreobjects">' + icon + '<span>Get more items...</span></li>');
} else {
$('#status').html('Loaded : ' + countFolders + ' folder(s), ' + countFiles + ' item(s) from S3');
}
}
function getObject(key) {
var params = {Bucket: AWS_BucketName, Key: key, Expires: AWS_SignedUrl_Expires};
var url = bucket.getSignedUrl('getObject', params);
return url;
//window.open(url, url);
}
function scrollToBottomListObjects() {
$('#contents').scrollTop($('#contents').prop("scrollHeight"));
}
function init() {
$('#headertitle').html(TITLE);
}
$( document ).ready(function() {
init();
listObjects(AWS_Prefix);
});
</script>
Below is the code that formats the jplayer code. I am trying to get the "Poster" path. If I get it correct, then it will display properly...
bucket.listObjects(
{
MaxKeys: AWS_MaxKeys,
Prefix : '<?php echo $_REQUEST['p']; ?>',
Delimiter : '/'
},
function (err, data)
{
if(data.Contents.length)
{
var prefix = '<?php echo $_REQUEST['p']; ?>';
for(var countAws=1; countAws < data.Contents.length; countAws++)
{
var key = data.Contents[countAws].Key;
var fileName = key.replace(prefix, '');
var linkAws = getObject(key);
var newlinkAws = linkAws.split('?');
var links = newlinkAws[0];
console.log(links);
myPlaylist.add({
title:""+fileName+"",
artist:"Artist",
mp3:links,
oga:links,
poster: ""+currentFolder+"".jpg //<--- HERE IS THE ISSUE
});
}
}
}
)
******* The code "poster: ""+currentFolder+"".jpg" above is where the problem is.
The absolute link to the example I gave above would be:
AWSS3/musicpax/mpx_music/Beatles-Greatest-Hits/Beatles-Greatest-Hits.jpg
But since this is dynamic, I cant use an absolute link. Can you provide any insight from the code at the top - that will lead to the correct path configuration.
Thank you in advance for any help.
This pulled the name from the link (path)... where it says 'HERE'
for(var countAws=1; countAws < data.Contents.length; countAws++)
{
var key = data.Contents[countAws].Key;
var fileName = key.replace(prefix, '');
var linkAws = getObject(key);
var newlinkAws = linkAws.split('?');
var links = newlinkAws[0];
/* Gets Album name HERE */
var album = links;
album = album.split("/");
album_name = (album[4]);
console.log(links);
myPlaylist.add({
title:""+fileName+"",
artist:""+album_name+"",
mp3:links,
oga:links,
poster: " "
});
}

Extracting image from API

Trying to output an image from an API but I keep getting an error "Empty JSON string"
function getIcon2(id)
{
var api = "http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=";
var data2 = JSON.parse(UrlFetchApp.fetch(api + id));
return data2.item.icon_large;
}
function iconTest(){
var icon = getIcon2(itemsheet.getRange("C2").getValue());
itemsheet.getRange("D18").setValue(data2);
}
I figured it out.
function getIcon() {
for(var i = 2; i < 500; i++) {
id = itemsheet.getRange("C" + i).getValue()
if(id == "")
return; //If the cell is empty, ignore it.
try {
target = itemsheet.getRange("B" + i);
var api = "http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=";
var raw = UrlFetchApp.fetch(api + id);
var data = JSON.parse(raw);
formula = "=image(\"" + data.item.icon_large + "\",1)";
target.setFormula(formula);
} catch(err) {
Logger.log("getIcon...." + err)
return;
}
}
}

Categories