How to update background of page dynamically with Flickr API - javascript

Edit: Static source urls can be constructed for Flickr images. Explanation:
https://www.flickr.com/services/api/misc.urls.html
I am making an ajax request to grab photos and I would like to parse this information in order to update the background of the page.
This is rough code:
$.ajax({
url: 'https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=[API_KEY]&safe_search=&lat=' + geoLat + '&lon=' + geoLong + '&format=json&nojsoncallback=1',
error: function() {
console.log('FlickerAPI Error');
},
success: function(data) {
var photoID = data.photos.photo[0].id;
var ownerID = data.photos.photo[0].owner;
var backgroundImageUrl = 'http://www.flickr.com/photos/' + ownerID + '/' + photoID + '/';
$('body').css('background-image','url(backgroundImageUrl)');
},
always: function() {
console.log('finished flicker');
}
});
When I log to the console this info, I get this error:
GET http://localhost:4567/backgroundImageUrl 404 (Not Found).
But when I log out the backgroundImageUrl I get: http://www.flickr.com/photos/[the right photo id]/[the right user id]/ which if I follow the link, takes me to the page that I want.
I've searched the docs, and it looks like they don't pass a url attribute.
Is this a problem with using localhost? Is there a better way to update the background with an image? Thanks

You are using the string literal backgroundImageUrl rather than using the contents of the variable (the actual url). Because that string doesn't contain a host or protocol it thinks it is relative to the current request.
You need to append the value of the variable when making the url instead.
$('body').css('background-image','url(' + backgroundImageUrl + ')');

Related

Website not reading the correct local json

I have made a HTML site that reads a .json with javascript/jQuery and writes to it with PHP.
I then have a c++ backend that writes and reads to the same .json.
I want to be able to send what button is selected by the players to the c++.
The .json that javascript reads isn't always the .json that I have modified with PHP or C++.
It won't always have the updated data, the time to get the updated data can be instant, a few seconds or e few minutes.
I have tried to remove caching and I have checked that the file gets updated
To load the .json on the website I use:
var $JSONList = $('#JSONList');
$.getJSON("json/playerMode.json", function(json) {
console.log(json); // this will show the info it in firebug console
var stringed = JSON.stringify(json);
var response = JSON.parse(stringed);
console.log(response); // this will show the info it in firebug console
$.each(response, function(i, itt){
$JSONList.append( "</br>" + itt.Name + " has pressed: " + itt.Button + " :(())");
})
});
This is called by a <button>
Since this sometimes won't load the updated .json, is there some way that I can force javascript to load the local .json again?
First, let's make the assumption this url works - except the caching issue and address that and other things as noted.
Change from the shortcut "json/playerMode.json" to $ajax
Force to NOT cache the results
Added a fail just in case
fixed syntax for "<br />"
removed unneeded code as the JSON would be parsed already as long as it is valid. IF it is not valid JSON and it only returns "a string, that looks like JSON", you should use dataType: "text json" to force jQuery conversion/parse
or consider using a converter (see below)
MIGHT need header('Content-Type: application/json') for PHP
if you are NOT returning a true JSON string, use a converter to make it into one, see Using Converters here: https://api.jquery.com/jQuery.ajax/
This from https://api.jquery.com/jquery.ajax/
Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET
parameters.
$.ajax({
type: "GET",
url: "json/playerMode.json",
cache: false,
data: "",
dataType: "json" // force automatic parse of the JSON string returned
}).done(function(json) {
console.log(json); // this will show the info it in firebug console
// should not need
// var stringed = JSON.stringify(json);
// not needed, see above
// var response = JSON.parse(json);
//console.log(response); // this will show the info it in firebug console
//$JSONList - what is this? it should be in here somewhere...so I did that
let $JSONList = $('#JSONList');
// should be parsed already, so changed to that
$.each(json, function(i, itt) {
$JSONList.append("<br />" + itt.Name + " has pressed: " + itt.Button + " :(())");
}).fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="JSONList"></div>

Using USDA REST API

I can't seem to figure out how to use USDA REST API no matter how hard I try. I've taken about 6 different online tutorials on how to use REST APIs all of which do not work with this particular API (I'm sure it's something small I'm missing but I've wasted countless hours doing/watching tutorials with no success).
Here's the link to their API:
https://ndb.nal.usda.gov/ndb/doc/apilist/API-FOOD-REPORT.md
Here's what I'm typing in my JavaScript:
xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.nal.usda.gov/ndb/reports/", true);
console.log(xhr.status);
The API says to pass your API KEY in parameters, but that makes no sense to me as every single tutorial I have read does not explain how to pass a KEY as a parameter... If someone would mind taking a moment to write the code necessary to access this API I would be greatly indebted.
UPDATE: I've also tried the JQuery method as follows:
$.get(
"http://api.nal.usda.gov/ndb/reports",
{
"api_key": "API KEY",
"ndbno": "01009"
},
function(data) {
console.log(data);
}
);
With no luck.
UPDATE 2: After leaving the JQuery example in for about 5 minutes, I get an error in the chrome console that says:
XMLHttpRequest cannot load http://api.nal.usda.gov/ndb/reports?api_key=(my API KEY)&ndbno=01009. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 403.
FINAL UPDATE: Problem was with my ISP apparently. Need to deal with that :(
The document you reference has a sample request URL:
http://api.nal.usda.gov/ndb/reports/?ndbno=01009&type=b&format=xml&api_key=DEMO_KEY
You just need to replace the ndbno, type, format and api_key values (the bits that come after the "="). For instance if your API key was 12345, you would need to change it like so:
http://api.nal.usda.gov/ndb/reports/?ndbno=01009&type=b&format=xml&api_key=12345
A complete, albeit "poor", implementation would be:
var apiKey = "DEMO_KEY";
var ndbno = "01009";
var type = "b";
var format = "json";
var url = "http://api.nal.usda.gov/ndb/reports/?ndbno=" + ndbno + "&type=" + type + "&format=" + format + "&api_key=" + apiKey;
$.get(url, function( data ) {
alert( "Data Loaded: " + JSON.stringify(data) );
});
Using the 'DEMO_KEY' provided by USDA I can get back a JSON result using the following code pasted into an HTML file (based on code from your on-going discussion with #BlakeH):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$( function() {
$.get(
"http://api.nal.usda.gov/ndb/reports",
{
"api_key": "DEMO_KEY",
"ndbno": "01009"
},
function(data) {
console.log(data);
console.log( JSON.stringify(data, null, ' '))
}
);
});
</script>
No issues with CORS were encountered with this code.
Is there any chance that you submitted more than 1000 requests in the past 24 hours?

JQuery 3D Gallery (SnowStack) – how do I call images from my server instead of flickr?

I recently discovered SnowStack, which allows for the creation of a 3D-style gallery, the effect can be seen here http://www.satine.org/research/webkit/snowleopard/snowstack.html
I'm going through the source code now, because I'm trying to find a way of getting it to load images off my server instead of loading random images from Flickr using the Flickr API.
If I had a guess, it's somewhere around here that changes need to be made, but I am a bit of a novice at JavaScrip/JQuery, so would appreciate if someone could help me with the correct way to tweak the code so as to make it load images from a folder on my server instead.
function flickr(callback, page)
{
var url = "http://api.flickr.com/services/rest/?method=flickr.interestingness.getList&api_key=60746a125b4a901f2dbb6fc902d9a716&per_page=21&extras=url_o,url_m,url_s&page=" + page + "&format=json&jsoncallback=?";
jQuery.getJSON(url, function(data)
{
var images = jQuery.map(data.photos.photo, function (item)
{
return {
thumb: item.url_s,
zoom: 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '.jpg',
link: 'http://www.flickr.com/photos/' + item.owner + '/' + item.id
};
});
callback(images);
});
}
There's also a tiny bit of documentation available, which alas does not seem to operate as suggested: https://code.google.com/p/css-vfx/wiki/SnowStack
Many thanks in advance and feel free to suggest better alternatives to this SnowStack Gallery that you think are better fitted/ more browser-friendly than this!
Your server needs to have url on it that returns a json array with three links for each image, or enough information to construct those three links. You could do this with nodejs, or asp.net mvc, or even a hard-coded response to start with. I'll give a quick explanation about what's going on:
var url = "http://api.flickr.com/services/rest/?method=flickr.interestingness.getList&api_key=60746a125b4a901f2dbb6fc902d9a716&per_page=21&extras=url_o,url_m,url_s&page=" + page + "&format=json&jsoncallback=?";
This a "RESTful API endpoint" which returns images from flickr (basically a URL that you can call, that tells you about a bunch of images).
jQuery.getJSON(url, function(data)
Makes an ajax call to get the data from the url. It returns a whole bunch of json, but you'll see further below, that we're only after the data.photos.photo items, the data looks something like:
"photo":
[
{
"id":"8707154801",
"owner":"38142969#N00",
"secret":"64b33dfc7b",
"server":"8401",
"farm":9,
"title":"Veyron",
"ispublic":1,
"isfriend":0,
"isfamily":0,
"url_m":"http:\/\/farm9.staticflickr.com\/8401\/8707154801_64b33dfc7b.jpg",
"height_m":"332",
"width_m":"500",
"url_s":"http:\/\/farm9.staticflickr.com\/8401\/8707154801_64b33dfc7b_m.jpg",
"height_s":"159",
"width_s":"240"
},// ...
]
The next bit of code consumes an array of these, and you can see that it doesn't use all the fields, just enough to create the links it needs. Your server could just return those links directly if you like.
var images = jQuery.map(data.photos.photo, function (item)
{
return {
thumb: item.url_s,
zoom: 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '.jpg',
link: 'http://www.flickr.com/photos/' + item.owner + '/' + item.id
};
});
For each record in the array returned from the url, this code produces a new item, with three urls in it, one for the thumbnail (which you see by default), one for the "zoomed in thumbnail", which it seems you get by hitting space, and one for the link to take you to if you click. The images variable ends up being an array of these objects, which is passed to the callback function, which I presume generates the view:
callback(images);
So ultimately what you need to do is make a url on your server that returns enough information to construct three urls, and then have a similar function to map your returned data into a list of { thumb, zoom, link } objects. You could just make your server return that data directly, and then you wouldn't need the mapping function.
EDIT
Ok, so how would you return this data from a server? I'll use node as a quick and dirty example, we'll create a server that simply returns a couple of items that exactly fit the data needed.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(JSON.stringify([{
thumb: "http://example.com/image1_thumb.jpg",
zoom: "http://example.com/image1_zoom.jpg",
link: "http://example.com/image1.jpg"
},
{
thumb: "http://example.com/image2_thumb.jpg",
zoom: "http://example.com/image2_zoom.jpg",
link: "http://example.com/image2.jpg"
}]));
}).listen(1337, '127.0.0.1');
With this data you could simply use the following code when getting the url:
var url = "http://127.0.0.1:1337";
jQuery.getJSON(url, function(data) {
callback(data);
});

javascript not running when logging in with different username

so i have a website made in ASP.NET that uses JS to generate some DOM elements after getting settings from the users account.
problem is that after i sign out and log in with a different user name i get the generated elements from the previous user and i don't know why. the code that generates the elements is as follows:
$.ajax({
url: '#Url.Content("~")' + 'Ticket/GetTvrtke',
async: false,
success: function (data) {
document.getElementById("header_tvrtka_holder").innerHTML = data;
}
});
and a little afterward its is used as such:
var tvrtke = document.getElementById("header_tvrtka_holder").innerHTML.split(", ");
$.each(tvrtke, function (index, value) {
$("#KlijentMultiSelect").append("<option value=\"" + value + "\" id=\"" + index + "\" >" + value + "</option>");
});
now when i log off and sign in as a different user the ajax code above doesn't trigger the getTvrtke URL that gets the settings wich generate the elements and i don't know why.
Ajax by default caches the response of the calls. YOu can set it to false so that there is a fresh request every single time by using the below at the top of your application.
$.ajaxSetup({cache: false});

Cross-domain requests with JQuery using YQL

So I need to make a a cross domain request where the response is not JSON formatted, so I cannot use .getJSON. .get obviously doesn't work because it is a cross domain request.
I came across this (Read this) when I was googling and it seems it should work for what I want to do (which is do a cross domain call that isn't json formatted using a jquery plug in). My code looks like the following. I know the url works fine because if I paste it into my browser, I can see the response, which according to last.fm documentation
The body of the server response
consists of a series of \n (ASCII 10)
terminated lines. A typical successful
server response will be something like
this:
OK
17E61E13454CDD8B68E8D7DEEEDF6170
http://post.audioscrobbler.com:80/np_1.2
http://post2.audioscrobbler.com:80/protocol_1.2
So I know my URL is fine. Now I am wondering how I get at this information, and why my version of their example does not work.
function performHandshake(sk, token, ts){
var token = md5(apiSecret + ts);
var urlToUse = "http://post.audioscrobbler.com/?hs=true&p=1.2.1&c=tst&v=1.0&u=chamals&t=" + ts + "&a=" + token + "&api_key=" + apiKey + "&sk=" + sk + "&format=xml&callback=cbfunc";
$('#container').load(urlToUse);
$.ajax({
url: urlToUse,
type: 'GET',
success: function(res){
var headline = $(res.responseText).find('a.tst').text();
window.console.log(headline);
}
});
}
Well the page you linked you talks about using YQL and jQuery. It's a very interesting solution. However, your example seems to skip over the YQL part (which is crucial).
var urlToUse = "http://post.audioscrobbler.com/?hs=true&p=1.2.1&c=tst&v=1.0&u=chamals&t=" + ts + "&a=" + token + "&api_key=" + apiKey + "&sk=" + sk + "&format=xml&callback=cbfunc";
var yqlUrl2Use = "http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(urlToUse)+
"%22&format=xml'&callback=?"
// this function gets the data from the successful
// JSON-P call
Then you'll have to call the call the new URL as a JSONP req...
$.getJSON(yqlUrl2Use, function(json){
// figure out the format of the answer here...
});
Yeah, cross browser scripting. You can't AJAX anything like that since it violates the same domain policy.
You are going to have to setup a proxy on the same server the JavaScript is running from.
Edit Lookslike you need the $('#container').load(url) bit for that to work.
Go back an reread the linked article carefully.
You need to use $.getJSON rather than $.ajax() to return cross site information.
The var res actually has my information that I needed. I guess their headline = part was specifically for their implementation.
Thanks to those who helped!

Categories

Resources