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
I've written some scripts to convert the pagination (20 photos per ajax request) from instagram json feeds to csv for easily storing the photo urls in our database. Our CMS is automatically able to convert CSV files into SQl files either by replacing the table or by appending to it. The problem is it will only work if ALL of the columns are the same.
It's close to totally working but I can't import my generated csvs because they keep getting an empty column where it should be line breaking to a new row because the final CSV output contains a comma + line break when it should only be returning the line break (i.e. without a trailing comma).
Encoding is UTF-8 and line breaks are being added using "\n". I've tried console logging just about every step of the process and it seems that there that
Here's a picture of one of the CSVs I am generating: http://screencast.com/t/dZfqN08A
Below is all the relevant code:
First I'm using ajax with a jsonp callback to load instagram photos based on a hashtag.
Photos are loaded like this:
function loadNext(nextUrl) {
$.ajax({
url: url,
cache: false,
type: 'POST',
dataType: "jsonp",
success: function(object) {
console.log('loadmore');
if (object) {
console.log(object);
$('.loadmore').fadeOut(500);
// chargement photos gallerie
$.each( object.data, function(home, photo) {
photo = '<div class="photo photo-load">' +
'<img class="pull-me" src="' + photo.images.low_resolution.url + '" height="380px" width="380px" alt="photo">' +
'<div class="dot"></div>' +
'<div class="share" >' +
'<!-- AddThis Button BEGIN -->' +
'<div class="addthis_toolbox addthis_default_style addthis_16x16_style">' +
'<a class="addthis_button_twitter"></a>' +
'<a class="addthis_button_facebook"></a>' +
'</div>' +
'<!-- AddThis Button END -->' +
'</div>' +
'<div class="text-photo">' +
'<div class="svg line w-line"></div>' +
'<h4 class="left">'+ photo.user.username + '</h4>' +
'<h4 class="right share-photo">PARTAGE</h4>' +
'</div>' +
'<div class="vote w-path-hover">' +
'<div class="fb-like" data-href="http://dev.kngfu.com/maurice/" data-layout="box_count" data-action="like" data-show-faces="false" data-share="false"></div>' +
'<div class="insta-like">' +
'<div class="count-box">' +
'<p>'+ photo.likes.count + '</p>' +
'</div>' +
'<a class="insta-button" title="Pour appuyer votre proposition préférée, rendez-vous sur Instagram." href="http://instagram.com/" ><i class="fa fa-instagram"></i>J aime</a>' +
'</div> ' +
'<div class="w-path"></div>' +
'<div class="base-cross"></div>' +
'<h4 class="vote-button">VOTE</h4>' +
'</div>' +
'</div>';
$(photo).appendTo( $( ".gallery" ) );
});
url = object.pagination.next_url;
console.log(url);
} else {
console.log("error");
}
} // end success func.
});
}
Then in a separate ajax call I can convert the same json feed to a csv file using this function (this function also calls a couple other functions so the dependent functions are included below the ajax call):
function convertJSON (nextUrl) {
$.ajax({
url: url,
cache: false,
type: 'POST',
dataType: "jsonp",
success: function(object) {
if (object) {
console.log(object);
var fromJSON = new Array();
i = 0;
$.each( object.data, function(home, photo) {
i++;
var photopath = photo.images.low_resolution.url;
var postID = photo.id;
var userID = photo.user.id;
var user = photo.user.username;
// watch out for those wild fullnames in instagram json
var fullname = photo.user.full_name;
fullname = fullname.replace(/[^a-z0-9]+|\s+/gmi, " ");
//console.log(fullname);
var likes = photo.likes.count;
var winner = 0;
var winnerplace = " ";
var campaign = "maurice1";
var timestamp = photo.created_time;
// easydate field formatting
var date = new Date();
date.setSeconds( timestamp );
var photodeleted = 0;
// add new rows to csv
var linebreak = "\n";
var arrayFromJSON = new Array( linebreak+photopath,
postID,
userID,
user,
fullname,
likes,
winner,
winnerplace,
campaign,
timestamp,
date,
photodeleted );
fromJSON[i] = arrayFromJSON.join();
});
//url = object.pagination.next_url;
//console.log(url);
//console.log( fromJSON );
makeCSV( fromJSON );
} else {
console.log("error");
}
} // end success func.
});
}
// json to csv converter
function makeCSV (JSONData) {
//console.log("makeCSV() function was started");
var data = encodeURIComponent(JSONData);
var currentTime = new Date().getTime();
var date = getDate( currentTime );
//console.log(JSONData);
var fileName = date;
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
+ "photopath," // now 12 strings which are the CSV's column titles
+ "postid,"
+ "userid,"
+ "username,"
+ "fullname,"
+ "likes,"
+ "winner,"
+ "winnerplace,"
+ "campaign,"
+ "creationdate,"
+ "easydate,"
+ "photodeleted"
+ data; // finally append our URI encoded data
console.log(uri);
// generate a temp <a /> tag that will auto start our download when the function is called
var link = document.createElement("a");
link.id = new Date().getTime();
link.href = uri;
// link visibility hidden
link.style = "visibility:hidden";
link.download = fileName + ".csv";
// append anchor tag and click
$("div#hidden").append(link);
link.click();
//document.body.removeChild(link);
}
// this function just makes human readable dates for CSV filename and id of our link tag
function getDate() {
var date = new Date();
//zero-pad a single zero if needed
var zp = function (val){
return (val <= 9 ? '0' + val : '' + val);
}
//zero-pad up to two zeroes if needed
var zp2 = function(val){
return val <= 99? (val <=9? '00' + val : '0' + val) : ('' + val ) ;
}
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
var h = date.getHours();
var min = date.getMinutes();
var s = date.getSeconds();
var ms = date.getMilliseconds();
return '' + y + '-' + zp(m) + '-' + zp(d) + ' ' + zp(h) + 'h' + zp(min) + 'm' + zp(s) + 's';
}
From all the console logging I've done, I can definitely assure you that I'm getting no trailing comma until the final step where the json array data gets URI encoded.
Since this extra column is also included in the header row I'm wondering if it has to do with this line?
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
I've also tried ISO-8859-1 encoding but I get the same result.
Does anyone know why this is happening? Any help would be appreciated
Your passing an array of lines to encodeURIComponent. That will stringify the array, joining it with a comma - which you don't want.
What you should do is
var arrayFromJSON = new Array( photopath,
// remove linebreak here ^
postID,
userID,
user,
fullname,
likes,
winner,
winnerplace,
campaign,
timestamp,
date,
photodeleted );
fromJSON[i] = arrayFromJSON.join(",");
// make comma explicit: ^^^
…
makeCSV( fromJSON );
…
var data = encodeURIComponent(JSONData.join("\n"));
// join the lines by a linebreak: ^^^^
…
var uri = "data:text/csv;charset=utf-8," // sets mime/data type
+ "photopath," // now 12 strings which are the CSV's column titles
+ "postid,"
+ "userid,"
+ "username,"
+ "fullname,"
+ "likes,"
+ "winner,"
+ "winnerplace,"
+ "campaign,"
+ "creationdate,"
+ "easydate,"
+ "photodeleted"
+ "\n"
// ^^^^^^ add linebreak
+ data; // finally append our URI encoded data
i have a JavaScript code of photo gallery with a slider but there's a problem :
var partnum = "<%Response.Write(Request.QueryString["partno"]); %>";
// check if the file is exiset -- it's running in bar() function -- run on servers and local host.
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('GET', url, false);
http.send();
return http.status != 404;
}
// push images paths to array
function bar() {
var exict = 0;
var counter = 0; //counter of array's index
for (var i = 1 ; exict < 30; i++) {
// if there isn't .jpg or .gif
if (!UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif")) {
exict = exict + 1;
}
// if there is .jpg
if (UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif")) {
arrOfImgs.push("/assets/catalog/parts/" + partnum + "_" + i + ".jpg");
counter = counter + 1;
}
// if there is .gif
if (UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".gif") && !UrlExists("/assets/catalog/parts/" + partnum + "_" + i + ".jpg")) {
arrOfImgs.push("/assets/catalog/parts/" + partnum + "_" + i + ".gif");
gifIndex.push(i);
counter = counter + 1;
}
}
}
but it was not work, so i tried to change var partnum
var partnum = <%= new JavaScriptSerializer().Serialize(Request.QueryString['partno']) %>;
but I got error: "error CS1012: Too many characters in character literal". I'm still not sure that this is the issue, as my original code does work (you can see the initial product image loaded when you visit the site .baumhaus and click on a product range and then any product, you will see the action - before it disappears once it tries to render the thumbnails).
How about
var partnum = '<%= Request.QueryString["partno"] %>'";
I have written JavaScript outside the <body> end tag. Firebug is unable to detect the JavaScript and I am unable to detect the JavaScript error.
Here is my code:
</body>
<script type="text/javascript">
function displayIFrameContent()
{
var iFrame = document.getElementById("link");
var if1= "<iframe src='http://leadmarket.hol.es/forms/solar-power.php?adv_id=" + <?php echo($fetch_users_data['id']); ?>;
var if2= "<iframe src='http://leadmarket.hol.es/forms/kitchen-installation.php?adv_id=" + <?php echo($fetch_users_data['id']); ?>;
var if3= "<iframe src='http://leadmarket.hol.es/forms/conservatory.php?adv_id=" + <?php echo($fetch_users_data['id']);; ?>;
var host = document.getElementById("host");
var subId = document.getElementById("subid");
var errorClass = "box form-validation-error border-width-2";
if(host.value == "")
changeClass("host", errorClass);
if(host.value != "")
{
var iFrameEnd = " width='280' height='330' frameborder='0' scrolling='no'></iframe>";
var leadTypeSelect = document.getElementById("leadType");
var leadTypeValue = leadTypeSelect.options[leadTypeSelect.selectedIndex].value;
iFrame.value = "";
if(leadTypeValue == 1)
iFrame.value = if1 + "&" + "sub_id=" + subId.value + "&source=" + host.value + "'" + iFrameEnd;
if(leadTypeValue == 2)
iFrame.value = if2 + "&" + "sub_id=" + subId.value + "&source=" + host.value + "'" + iFrameEnd;
if(leadTypeValue == 3)
iFrame.value = if3 + "&" + "sub_id=" + subId.value + "&source=" + host.value + "'" + iFrameEnd;
}
}
function changeClass(id, classname)
{
document.getElementById(id).setAttribute("class", classname);
}
</script>
</html>
Your help will be appreciated. Thanks in advance!
The code above contains PHP tags, which cause some syntax errors. In this case the Script panel just shows a message "No Javascript on this page". You should make sure they are interpreted by PHP before they are output to the browser.
Also JavaScript syntax errors are listed within the Console Panel. Make sure you have the option Show JavaScript Errors checked to see them.
Furthermore there's a detailed description about script debugging available within the Firebug wiki.
Sebastian
var rows = [];
for (var id in topics) {
var topic = g_favoriteTopics[topics[id].id];
var $row = $("table#Favorites tr#topicTemplate").clone();
alert(topic.title);
$row.find("td.txtCol a").html(topic.title);
var href = commonVariables.formAction +
"?PARTITION_ID=" + commonVariables.partitionId +
"&CONFIGURATION=" + commonVariables.configurationId +
"&CMD=DFAQ&DFAQ_TOPIC_ID=" + topic.id +
"&DFAQ_TOPIC_TYPE=" + topic.type;
$row.find("td.txtCol a").attr("href", href);
$row.find("td.imgCol input").attr("topicId", topic.id);
rows.push(topic.title.toLowerCase() + "<<<>>><tr topicId=" + topic.id + ">" + $row.html() + "</tr>");
}
The alert window shows the proper topic title (name of the topic).However Iam presented with a Javascript error (title is null or not an object),after the alert.
It runs fine in FF and chrome