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.
Related
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.
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.
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: " "
});
}
Where I'm At
I'm making a form for an online silent auction. People click a button, choose one of six fixed amounts $10, $25, $50, $100, $250, $500 and that amount gets added to the last bid, giving us total amount of their new bid.
Problem
It takes an extraordinarily long time (4-5 seconds after the button is clicked) to replace the tk-amount placeholder using.html to .current__amount and .new__amount and display these two pieces of data grabbed from a Google Spreadsheet using an AJAX call to the SheetsU API.
I have a feeling it's because of how much stuff is being done everytime a button is clicked. Is there a better way to approach this?
scripts.js
// Bid Options
$(".button__form").on('click', function(){
var btnSelected = $(this).hasClass("is-selected");
var sectionOneCompleted = $(".check--one").hasClass("is-completed");
if (btnSelected) {
$(this).removeClass("is-selected");
$(".check--one").css("color", "#ccc");
} else {
$(".button__form").removeClass("is-selected");
$(this).addClass("is-selected");
$(".check--one").css("color", "#ffdc00");
}
});
$(".button__form").on("click", function() {
var lastbtnClicked = ($(this).attr("class"));
// Bid Options
var buttonOne = $(this).hasClass("button__one");
var buttonTwo = $(this).hasClass("button__two");
var buttonThree = $(this).hasClass("button__three");
var buttonFour = $(this).hasClass("button__four");
var buttonFive = $(this).hasClass("button__six");
var buttonSix = $(this).hasClass("button__six");
// Bid Values
var buttonOneValue = 10;
var buttonTwoValue = 25;
var buttonThreeValue = 50;
var buttonFourValue = 100;
var buttonFiveValue = 250;
var buttonSixValue = 500;
/*-------------------------------------
API: SHEETSU
--------------------------------------*/
$.ajax({
url: "https://sheetsu.com/apis/4a8eceba",
method: "GET",
dataType: "json"
}).then(function(spreadsheet) {
// Get and print data
var currentBid = parseInt(spreadsheet.result.pop().Bids);
console.log(currentBid);
var phoneNumber = "1" + spreadsheet.result.pop()["Phone Number"];
var printBid = $(".current__amount").html("$" + currentBid);
console.log(printBid);
if (buttonOne) {
$(".new__amount").html("$" + (currentBid + buttonOneValue));
} else if (buttonTwo) {
$(".new__amount").html("$" + (currentBid + buttonTwoValue));
} else if (buttonThree) {
$(".new__amount").html("$" + (currentBid + buttonThreeValue));
} else if (buttonFour) {
$(".new__amount").html("$" + (currentBid + buttonFourValue));
} else if (buttonFive) {
$(".new__amount").html("$" + (currentBid + buttonFiveValue));
} else if (buttonSix) {
$(".new__amount").html("$" + (currentBid + buttonSixValue));
}
});
});
Are you sure your "performance issues" arn't actually caused by your http request taking 4-5 seconds to complete? To check open your browsers console and click on the network tab. Then press your button. You should see a request send out and how long it takes to complete.
Lets go one by one
Take these out of callback, no need to reinitialize for every click.
// Bid Values
var buttonOneValue = 10;
var buttonTwoValue = 25;
var buttonThreeValue = 50;
var buttonFourValue = 100;
var buttonFiveValue = 250;
var buttonSixValue = 500;
Reduce below
$(".button__form").on('click', function(){
var btnSelected = $(this).hasClass("is-selected");
var sectionOneCompleted = $(".check--one").hasClass("is-completed");
if (btnSelected) {
$(this).removeClass("is-selected");
$(".check--one").css("color", "#ccc");
} else {
$(".button__form").removeClass("is-selected");
$(this).addClass("is-selected");
$(".check--one").css("color", "#ffdc00");
}
});
to this
$(".button__form").on('click', function(){
$(this).toggleClass("is-selected");
$(".check--one").toggleClass("is-completed");
});
//And adjust the color of .check--one in css
And use the class property efficiently
if (buttonOne) {
$(".new__amount").html("$" + (currentBid + buttonOneValue));
} else if (buttonTwo) {
$(".new__amount").html("$" + (currentBid + buttonTwoValue));
} else if (buttonThree) {
$(".new__amount").html("$" + (currentBid + buttonThreeValue));
} else if (buttonFour) {
$(".new__amount").html("$" + (currentBid + buttonFourValue));
} else if (buttonFive) {
$(".new__amount").html("$" + (currentBid + buttonFiveValue));
} else if (buttonSix) {
$(".new__amount").html("$" + (currentBid + buttonSixValue));
}
to something like this in for loop
$(".new__amount."+buttons[i].class).html("$" + (currentBid + buttons[i].value));
var buttons = [{class:"buttonSix", value:123},....]
So at last your code could look like this.
// Bid Options
var buttons = [{class:"buttonOne", value:12},....{class:"buttonSix", value:123}]
$(".button__form").on('click', function(){
$(this).toggleClass("is-selected");
$(".check--one").toggleClass("is-completed");
//And adjust the color of .check--one in css
var lastbtnClicked = ($(this).attr("class"));
/*-------------------------------------
API: SHEETSU
--------------------------------------*/
$.ajax({
url: "https://sheetsu.com/apis/4a8eceba",
method: "GET",
dataType: "json"
}).then(function(spreadsheet) {
// Get and print data
var currentBid = parseInt(spreadsheet.result.pop().Bids);
console.log(currentBid);
var phoneNumber = "1" + spreadsheet.result.pop()["Phone Number"];
var printBid = $(".current__amount").html("$" + currentBid);
console.log(printBid);
var $btnForm = $(".button__form")
for(){
if($btnForm.hasClass(buttons[i].class)){
$(".new__amount.").html("$" + (currentBid + buttons[i].value));
}
}
});
});
I am trying to show a set of images that are within a certain time and at a given latitude and longitude. The Instagram API script is receiving an error in the console log. This is the error:
SyntaxError: Unexpected token ':'
Here is the code:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
var count = "20";
var access_token = "5567117.f59def8.65c6953a15e94932a44f9b4311aa8653";
var access_parameters = {access_token:access_token};
function grabImages(access_parameters) {
var instagramUrl = "https://api.instagram.com/v1/media/search?lat=54.963782&lng=-1.623423&max_timestamp=1354950000&min_timestamp=1354935600&distance=2000?callback=?&count=" + count;
$.getJSON(instagramUrl, access_parameters, onDataLoaded);
console.log(instagramUrl);
}
function onDataLoaded(instagram_data) {
if(instagram_data.meta.code == 200) {
var photos = instagram_data.data;
if(photos.length > 0) {
for (var key in photos) {
var photo = photos[key];
$("#target").append('<img src ="' + photo.images.thumbnail.url + '">');
$("#target").append('<span>' + photo.user.username +'</span>');
}
} else {
$("#target").append("Hmm. I couldn’t find anything!");
}
} else {
var error = data.meta.error_message;
$("#target").append('Something happened, Instagram said: ' + error);
}
}
grabImages(access_parameters);
});
</script>
Your query string has an extra ? before the callback param.
"https://api.instagram.com/v1/media/search?lat=54.963782&lng=-1.623423&max_timestamp=1354950000&min_timestamp=1354935600&distance=2000?callback=?&count="
should be
"https://api.instagram.com/v1/media/search?lat=54.963782&lng=-1.623423&max_timestamp=1354950000&min_timestamp=1354935600&distance=2000&callback=?&count="