In my Firefox OS app i use Flickr API to show relevant images, My URL for the call is like this.
https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&lat=42.86366&lon=-75.91438&radius=3&format=json&nojsoncallback=1
and i use created a function to call the flicker api for the images. This is the function where i create the URL with the api key and latitude and longitude for the api call
function displayObject(id) {
console.log('In diaplayObject()');
var objectStore = db.transaction(dbTable).objectStore(dbTable);
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
if (cursor.value.ID == id) {
var lat = cursor.value.Lat;
var lon = cursor.value.Lon;
showPosOnMap (lat, lon);
// create the URL
var url = 'https://api.flickr.com/services/rest/?method=flickr.photos.search';
url += '&api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
url += '&lat=' + lat + '';
url += '&lon=' + lon + '';
url += '&radius=3';
url += '&format=json&nojsoncallback=1';
$.getJSON(url, jsonFlickrFeed);
return;
}
cursor.continue();
} else {
$('#detailsTitle').html('No DATA');
}
};
}
This function gets the JSON object received from flickr. This function displays the thumbnails of the images in a jquery mobile grid.
function jsonFlickrFeed (data) {
console.log(data);
var output = '';
// http://farm{farmId}.staticflickr.com/{server-id}/{id}_{secret}{size}.jpg
for (var i = 0; i < data.photos.photo.length; i++) {
// generate thumbnail link
var linkThumb = '';
linkThumb += 'http://farm' + data.photos.photo[i].farm + '.staticflickr.com/' + data.photos.photo[i].server + '/' + data.photos.photo[i].id + '_' + data.photos.photo[i].secret + '_s.jpg';
// generate Full image link
var linkFull = '';
linkFull += 'http://farm' + data.photos.photo[i].farm + '.staticflickr.com/' + data.photos.photo[i].server + '/' + data.photos.photo[i].id + '_' + data.photos.photo[i].secret + '_b.jpg';
if (i < 20)
console.log(linkThumb);
//console.log(linkFull);
var title = data.photos.photo[i].title;
var blocktype = ((i % 3) == 2) ? 'c' : ((i % 3) == 1) ? 'b' : 'a';
output += '<div class="ui-block-' + blocktype + '">';
output += '<a href="#showphoto" data-transition="fade" onclick="showPhoto(\'' + linkFull + '\',\'' + title + '\')">';
output += '<img src="' + linkThumb + '_q.jpg" alt="' + title + '" />';
output += '</a>';
output += '</div>';
};
$('#photolist').html(output);
}
Then finally this function show the full screen view of the image. When the user taps on the thumbnail a larger image is taken and shown.
function showPhoto (link, title) {
var output = '<a href="#photos" data-transition="fade">';
output += '<img src="' + link + '_b.jpg" alt="' + title + '" />';
output += '</a>';
$('#myphoto').html(output);
}
My problem is that, i get the JSON object with the images by calling the API. i have console.log() where i output the json object and i checked all the image info is there. But when i go to the grid view and even the full view i get the default image that states that the This image or video is currently unavailable. I can't figure out what im doing wrong here.. Please help.
You may be requesting an image size that flickr does not have for that image. You are appending "_s", "_q" and "_b" to select a few sizes - so perhaps those are not available. You can check the flickr API 'photos.getSizes' to see what sizes are available. The Flickr API seems to be pretty inconvenient sometimes.
https://www.flickr.com/services/api/flickr.photos.getSizes.html
Related
Any help would be appreciate. I need to create a slider based on JSON datas from the moviedb API. I created the slider showing the title, the picture and the description within a for loop but the last thing I need to achieve is to get the movie rating but instead of the number I need to show stars (half or full filled according to the datas provided).
I'm stuck and tried different things but it doesn't work. I know it's quite simple but I'm stuck.
Many thanks for any help. Do not hesitate if you need something else because it's my first post on stackoverflow.
Here is the fiddle of my work :
https://jsfiddle.net/y2hbzej8/7/
Here is my JS code to get datas :
JS :
var urlmoviedb = 'https://api.themoviedb.org/3/movie/upcoming?api_key=e082a5c50ed38ae74299db1d0eb822fe';
$(function() {
$.getJSON(urlmoviedb, function (data) {
console.log(data);
for (var x = 0; x < data.results.length; x++) {
var title = data.results[x].original_title;
var descr = data.results[x].overview;
var note = data.results[x].vote_average;
var noteround = Math.round(2 * note) / 2;
var str = "/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg";
var imageurl = str.replace("/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg", "https://image.tmdb.org/t/p/w1280");
var image = imageurl + data.results[x].backdrop_path;
$('#image').append('<li>' + '<h2 class="h2-like mt-4">' + title + '</h2>' + '<p class="note">' + noteround + '</p>' + "<img class='img-fluid mb-4' src='" + image + "'>" + '<p class="descr">' + descr + '</p>' + '</li>');
}
});
Divide the vote_average field of each row by two since values go from 0 to 10. This will give you five stars based values.
I edited your example, I added font-awesome CSS library that will give you lots and lots of icons you can play with. Check them out
Here's the edited example on JSFiddle
var urlmoviedb = 'https://api.themoviedb.org/3/movie/upcoming?api_key=e082a5c50ed38ae74299db1d0eb822fe';
$(function() {
$.getJSON(urlmoviedb, function(data) {
console.log(data);
for (var x = 0; x < data.results.length; x++) {
var title = data.results[x].original_title;
var descr = data.results[x].overview;
var note = data.results[x].vote_average;
var noteround = Math.round(2 * note) / 2;
var str = "/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg";
var imageurl = str.replace("/jj8qgyrfQ12ZLZSY1PEbA3FRkfY.jpg", "https://image.tmdb.org/t/p/w1280");
var image = imageurl + data.results[x].backdrop_path;
//Translate vote average field into number of stars by dividing them by two since vote_average goes from 0 to 10
var numberOfStars = Math.round(note/2);
var stars = '';
for(var index = 0; index < numberOfStars; index++)
stars += '<span class="fa fa-star"/>';
$('#image').append('<li>' + '<h2 class="h2-like mt-4">' + title + '</h2>' + "<img class='img-fluid mb-4' src='" + image + "'>" + '<p class="descr">' + descr + '</p>' + stars + '</li>');
}
});
});
I wanted to get the profile photos per post of this site (https://medium.com/#femalefounderssg) using this javascript function but I am not getting the right photo. Please guide me in changing my code for me to get the appropriate photo. Thank you. Here is the code.
$(function () {
var $content = $('#jsonContent');
var data = {
rss_url: 'https://medium.com/feed/#femalefounderssg'
};
$.get('https://api.rss2json.com/v1/api.json', data, function (response) {
if (response.status == 'ok') {
var output = '';
$.each(response.items, function (k, item) {
var visibleSm;
if(k < 3){
visibleSm = '';
} else {
visibleSm = ' visible-sm';
}
output += '<div class="col-sm-6 col-md-4' + visibleSm + '">';
output += '<div class="blog-post"><header>';
output += '<h4 class="date">' + $.format.date(item.pubDate, "dd<br>MMM") + "</h4>";
var tagIndex = item.description.indexOf('<img'); // Find where the img tag starts
var srcIndex = item.description.substring(tagIndex).indexOf('src=') + tagIndex; // Find where the src attribute starts
var srcStart = srcIndex + 5; // Find where the actual image URL starts; 5 for the length of 'src="'
var srcEnd = item.description.substring(srcStart).indexOf('"') + srcStart; // Find where the URL ends
var src = item.description.substring(srcStart, srcEnd); // Extract just the URL
output += '<div class="blog-element"><img class="img-responsive" src="' + src + '" width="360px" height="240px"></div></header>';
output += '<div class="blog-content"><h4>' + item.title + '</h4>';
output += '<div class="post-meta"><span>By ' + item.author + '</span></div>';
var yourString = item.description.replace(/<img[^>]*>/g,""); //replace with your string.
var maxLength = 120 // maximum number of characters to extract
//trim the string to the maximum length
var trimmedString = yourString.substr(0, maxLength);
//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))
output += '<p>' + trimmedString + '...</p>';
output += '</div></div></div>';
return k < 3;
});
$content.html(output);
}
});
});
Current Profile Output:
Desired Profile Output:
You are getting the wrong image because the first result you get when searching for <img index is the author's image.
You need to skip the first result and get the second one:
Finding second occurrence of a substring in a string in Java [it's Java, but the concept remains]
var tagIndex = item.description.indexOf('<img', item.description.indexOf('<img') + 1);
String#indexOf supports a second argument as "fromIndex".
By adding 1 to the index of the first result we make sure that the first <img will not match, and instead the second <img will.
Simplified JSFiddle: https://jsfiddle.net/yuriy636/03n1hffh/
I am working on a website and I am looking to make the recipes pages dynamic. I created a JSON test database, created a JS file that retrieves values from the JSON file and displays them in appropriate divs on the page.
What i want to do is be able to choose the respectful JSON for each recipe and display it on the same page when a user clicks a link in the sidebar without having to create a ton of blank HTML pages with the same divs.
Below is my code. Hoping someone can help guide me thanks!
(function() {
'use strict';
var url = 'my json url';
$.getJSON(url, function(json) {
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
//retrieve values from dataArray
$.each(data[0], function (i, item) {
title += '<h1>' + item.recipeName + '</h1>';
image += '<img src="' + item.imageURL + '">';
directions += '<p>' + item.directions + '</p>';
prep += '<strong>' + item.prepTime + '</strong>';
cook += '<strong>' + item.cookTime + '</strong>';
serve += '<strong>' + item.servInfo + '</strong>';
});
//append results to div
$('#recipeTitle').html(title);
$('#recipeImage').html(image);
$('#recipeDirections').html(directions);
$('#recipePrep').html(prep);
$('#recipeCook').html(cook);
$('#recipeServes').html(serve);
var ul = $('<ul class="nav nav-stacked">').appendTo('#recipeIngredients');
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
});
})();
new code`(function() {
function callback(json){
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
//retrieve values from dataArray
$.each(data[0], function (i, item) {
title += '<h1>' + item.recipeName + '</h1>';
image += '<img src="' + item.imageURL + '">';
directions += '<p>' + item.directions + '</p>';
prep += '<strong>' + item.prepTime + '</strong>';
cook += '<strong>' + item.cookTime + '</strong>';
serve += '<strong>' + item.servInfo + '</strong>';
});
//append results to div
$('#recipeTitle').html(title);
$('#recipeImage').html(image);
$('#recipeDirections').html(directions);
$('#recipePrep').html(prep);
$('#recipeCook').html(cook);
$('#recipeServes').html(serve);
var ul = $('<ul class="nav nav-stacked">').appendTo('#recipeIngredients');
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
}
$('#pasta').click(function(){
$('#recipeIngredients').empty();
//get the url from click coresponding to the item
$.getJSON(url,callback);
});
//intially load the recipies with the URL
var url = '';
$.getJSON(url,callback);
})();`
to achieve code reusability , try calling the $.getJSON() with a reusable function (callback) on click of the link in the sidebar
(function() {
function callback(json){
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
.... //rest of the code
...
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
}
$('.sidebarLink').click(function(){
$('#recipeIngredients').empty()
//get the url from click coresponding to the item
$.getJSON(url,callback);
});
//intially load the recipies with the URL
var url = 'my json url';
$.getJSON(url,callback);
})();
I have generated multiple barcodes using this code:
function getCode() {
var multipleCodes = document.getElementById('codeArea').value;
var eachLine = multipleCodes.split('\n');
console.log("eachLine = " + eachLine);
for (var i = 0; i < eachLine.length; i++) {
console.log("Inside loop: " + eachLine[i]);
var div = document.createElement('iframe');
div.innerHTML = "";
div.setAttribute('id', 'iFrameID' + i);
document.body.appendChild(div);
document.getElementById('iFrameID' + i).src = 'barCodeGenerator/generateBarCode.php?q=' + eachLine[i];
}
and trying to print it by using this method:
function printDiv(divName) {
var strName = document.getElementById("codeArea").value;
var imageId = document.getElementsByClassName('decoded');
var imagObject = new Image();
imagObject = imageId;
var originalImage = '<img id="imageViewer" src="' + imageSrc + '" style="padding-top: 20px" alt="' + imageSrc + '" />';
popup = window.open('', 'popup', 'toolbar=no,menubar=no,width=700,height=650');
popup.document.open();
popup.document.write("<html><head></head><body onload='print()'>");
popup.document.write(originalImage);
popup.document.write("</body></html>");
window.close('popup');
popup.document.close();
setTimeout(function () { popup.close(); }, 8000);
}
which only print single image by merging all barcodes.
How can i print them separately as multiple images.
Any help will be appreciated.
The most part of this code is irrelevant to your question. Consider removing your logs, the parts about showing popup and hiding it for more clearance.
Seems imageSrc variable in your code contains the source of one image, so you need to change your code by sending the array of image sources and iterating over it:
var originalImage = '';
// assuming imageSrc is an array of image sources
for (var i=; i < imageSrc.length; i++) {
// note that I'm changing the id of the image a litle bit to ensure it will remain unique
originalImage += '<img id="imageViewer' + i + '" src="' + imageSrc[i] + '" style="padding-top: 20px" alt="' + imageSrc[i] + '" />';
}
then the rest of your code must work.
I'm sending an xmlhttprequest to youtube to get some videos. I have gone to the google developer's console and set up an api key with WORK URL I'm requesting from connected to it. When I try to run the script from WORK URL, I get an 'ipreferrer not allowed' error, even though I specified that url on my api key.
But when I connect the api key to MY OWN PERSONAL URL and run the same script from that url, it works fine. So when it's run from WORK URL it must be sending the wrong referral url to youtube.
The question is, how can I tell what referral url my xmlhttprequest is telling youtube it is coming from?
My code is below:
function createCORSRequest(myurl, cb)
{
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
if( typeof cb === 'function' )
cb(xmlhttp.responseText);
}
}
xmlhttp.open("GET",myurl,true);
xmlhttp.send();
}
function buildVideoMenu()
{
openDiv = true;
mainVideoTarget = 'main_video';
playlistID = 'PLAg45-Ox3WR4gODmcAmIYHVvCpngXcCTZ';
menuDiv = 'video_menu_images';
thumbnailDiv = 'thumb';
APIKey = 'AIzaSy...';
url = 'https://www.googleapis.com/youtube/v3/playlistItems?' +
'&part=snippet' +
'&maxResults=25' +
'&playlistId=' + playlistID +
'&key=' + APIKey;
//alert(url);
createCORSRequest(url, function(srchJSON) //Get JSON for search
{
myDivHTML = '';
myDiv = document.getElementById("video_menu_images"); //get div in variable
console.log("YouTube returned the json code: " + srchJSON);
srchObj = JSON.parse(srchJSON); //parse JSON for playlistItems
for(i=0;i<srchObj.items.length;i++) //For items in srchObj.items:
{
console.log("item number " + i);
if(srchObj.items[i].snippet.thumbnails!=undefined)
{
if(openDiv)
{
myDivHTML += '<div id = "tnvertblock">';
}
myDivHTML += ' <div class = "' + thumbnailDiv + '">';
//console.log(srchObj.items[i].snippet.title);
vidFrameURL = 'https://www.youtube.com/embed/' + srchObj.items[i].snippet.resourceId.videoId;
//console.log("url = " + vidFrameURL);
imgUrl = srchObj.items[i].snippet.thumbnails.default.url; //get thumbnail image url
myDivHTML += ' <a href = "' + vidFrameURL + '" target = "' + mainVideoTarget +'">';
myDivHTML += ' <img width = "120" height = "90" class = "thumbnail" src = "' + imgUrl + '" />';
myDivHTML += ' </a>';// Put in the item.snippet.thumbnails.default.url (its own div)
myDivHTML += ' </div>'; //close thumbnail div
if(!openDiv)
{
myDivHTML += '</div>';
}
openDiv = !openDiv;
}
}
//alert(myDivHTML);
myDiv.innerHTML = myDivHTML;
});
}
buildVideoMenu();
UPDATE: To clarify my question, here's a screenshot of the console developer's page with an explanation: