Background - I'm calling a JSON feed via jQuery's AJAX method. No issues here. One of the values in the feed points to an image URL on Instagram and I then render the image in html.
Here's the problem - most of the Instagram URLs come back fine and the image renders on my html page as expected but a couple of URLs return 404 errors and therefore render no image.
My question - is there a way to check for that 404 error and tell the code to do something else?
Code -
var $SS__image = j.mainasset;
$output += '<img src="' + $SS__image + '" />';
What I want to achieve -
var $SS__image = j.mainasset;
if($SS__image.ERROR === '404'){
$output = '';
}else{
$output = '<img src="' + $SS__image + '" />';
}
Is this possible? Thanks in advance!
How about
var $img = $("<img/>");
$img.on("error",function() {
$(this).remove();
});
$output.append($img);
$img.attr("src",$SS__image); // in this order
Related
I started working with APIs/Ajax/JSON recently and began a small project to test my knowledge.
I made a simply website where you type a word into a form and it brings back Flickr photos associated with the word.
It works pretty well, but it always includes a simple "undefined" before the first photo which messes with the display of the first row of pictures.
An example can be seen here, simply search for a photo tag and you'll see what I'm talking about:
http://codepen.io/anon/pen/jPExNm
Here is the related jQuery:
$('form').submit(function (evt) {
evt.preventDefault();
// the AJAX part
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
var query = $('#photoQuery').val();
var flickrOptions = {
tags: query,
format: "json"
};
function displayPhotos(data) {
var photoHTML;
$.each(data.items,function(i,photo) {
photoHTML += '<div class="photo">';
photoHTML += '<a href="' + photo.link + '" class="image">';
photoHTML += '<img src="' + photo.media.m + '"></a></div>';
}); // end each
$('#photoGallery').html(photoHTML);
}
$.getJSON(flickerAPI, flickrOptions, displayPhotos);
}); // end submit
I haven't found any errors related to this in the Javascript console and couldn't find anything like this while Googling, so I'm turning to StackOverflow. Thank you for any and all help.
Because
var photoHTML;
is the same thing as
var photoHTML = undefined;
Basic example of what you are doing
var str;
str = str + "123"; // undefined + "123" = "undefined123";
You need to set it to an empty string
var photoHTML = "";
I'm trying to get an image stored into a local filesystem. After that, I need to mount an html with this image from javascript.
So far, I'm getting the image with a servlet, and it's actually working as I can show the image in my JSP <img width="120" src="<%=IncVars.getParameter("ruta0")%>myImageServlet">
public class MyImageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//get the file image
File image = IncFunctions.getLogoFile();
// Get content type
String contentType = getServletContext().getMimeType(image.getName());
// Init servlet response.
response.reset();
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(image.length()));
// Write image content to response.
Files.copy(image.toPath(), response.getOutputStream());
}
//...
}
I'm trying to do the same to mount the html from a js function, but I can't find the way to generate a html with this image in my js function:
function mountTicket(text, idControl, servletPath){
document.getElementById(idControl).innerHTML = parseTicket(texto, imagePath);
window.print();
}
function parseTicket(texto, servletPath){
var textHtml = "";
//Call the servlet
$.get(servletPath, function(data) {
textoHtml = "<img width='120' src=" + data + "/>";
textoHtml += "<br />";
});
//..
textoHtml += "<div";
if (estilo != ""){
textoHtml += " style=\"" + estilo + "\"";
}
textoHtml += ">" + contenido + "</div>";
return textoHtml;
}
The data var get from the servlet are bytes, and it seems the js doesn't know how to interpret it. I've also tried to pass the path of the image, let's say "C:\myDirectory\myImage.png", but as I expected, it couldn't find it and show it.
Any help would be appreciated. Thanks in advance.
The answer was easier than I thought. I don't need to call the servlet from my js code, I just need to add the image with the servlet path.
Something like this:
textoHtml = "<div><img src='" + servletPath + "'> </div>" ;
And the browser will show the image.
Hope it can help someone with similar "issues"
I'm using AJAX to add more articles to a list of articles when you press a button. So my AJAX call returns data that includes a title, author and 1 to 3 images associated with the article. Below is the code I'm using to output it, but it feels VERY clunky.
What are the best practices for printing out HTML with JavaScript/jQuery in a scenario like this where I need to add many new tags with new information? Thanks for the help!
Also, I know some of the code isn't super well written because it's a first draft just to make stuff work, so please only answer this question with regards to printing out the HTML or things that will make printing the HTML easier
$j.getJSON(ajaxurl, {action: 'load_articles', issues: $issues}, function(data) {
if (data.message != null) {
alert(data.message);
return
}
list = $j('.all-articles ul');
for (i in data.articles) {
article = data.articles[i];
//Hides articles already on page
if ($j("#" + article.id).size() === 0) {
list.append('<li class="article-preview" id="' + article.id + '">' +
'<h3 class="article-headline">' + article.title + '</h3>' +
'</li>');
current = $j("#" + article.id)
current.append('<p class="authors"></p>');
authors = $j("#" + article.id + " .authors")
for (a in article.authors) {
authors.append(article.authors[a].data.display_name + " ");
}
current.append('<div class="images"></div>');
images = $j("#" + article.id + " .images")
for (i in article.image) {
text = "<div class='image-expand-container'>";
if (i == 0) {
text += ('<img id="' + article.image[i].id + '"class="selected" src="' + article.image[i].medium + '"></img>');
}
else {
text += ('<img id="' + article.image[i].id + '" src="' + article.image[i].medium + '"></img>');
}
text += '<div class="dashicons dashicons-editor-expand"></div></div>';
images.append(text);
}
}
}
There are a few approaches you can take.
As you're doing here, you can return data from your ajax call (e.g. as JSON) and then use a javascript function to generate the corresponding HTML by building strings. This, as you're finding, is often messy.
You can generate the actual HTML on the server side, and have the ajax call return an HTML fragment, which you insert into your DOM. This has the advantage that, if some of your HTML is loading when the page loads, and some is loading via ajax, you can use the same approach (PHP, XSLT, ASP.NET Razor, any kind of server-side templating) to generate all of the HTML.
You can use a javascript templating framework to turn your JSON data into HTML. If all of your HTML is being generated via javascript (e.g. in a single-page application) this may be your best bet.
I have a webpage that pulls in a channel's upload feed and displays them. Everything works fine in chromium but as I said, in FireFox it's all a lot slower or even crashing.
I don't even know where to begin finding the problem with this, the site's live so you can check it out here http://lartmagazine.co.uk/lart-tv/.
To display the main large video I'm using:
var gdata = 'http://gdata.youtube.com/feeds/api/users/LARTMagazine/uploads?alt=json&videoid?v=2&callback=?';
$.getJSON(gdata, function(data) {
var id = data.feed.entry[0].id.$t.split('/').reverse()[0];
var htmlString = '<iframe src="http://www.youtube.com/embed/' + id + '?wmode=transparent&version=3&vq=hd1080&showinfo=0&modestbranding=1&autohide=1" frameborder="0" allowfullscreen></iframe>';
$('#loader').hide();
$('#yTMain').append(htmlString);
});//end load iframe
And then I'm using this to pull the thumbnails:
var ytapiurl = 'http://gdata.youtube.com/feeds/api/users/LARTMagazine/uploads?alt=json&max-results=12&callback=?';
$.getJSON(ytapiurl, function(data) {
var list_data="";
$.each(data.feed.entry, function(i, item) {
var title = item['title']['$t'];
var thumbimg = item['media$group']['media$thumbnail'][0]['url'];
var ytlink = item['media$group']['media$player'][0]['url'];
list_data += '<div class="ytblock"><div class="videothumb"><a href="'+ ytlink +'"target="_blank">';
list_data += '<img src="'+thumbimg+'" /></div><div class="yttitle"><h2>'+ title + '</h2></div></a></div>';
});//end gdata
Is there something that I'm doing wrong with my data request that's lagging in FireFox for some reason? Other than that I have no idea.
If you need more information just ask.
Try to add the option "html5=1" - I am using iframes, but the YouTube API replaces your div with an iframe, so that should be the same.
src="//www.youtube.com/embed/VIDEOID?autoplay=1&html5=1&enablejsapi=1
Could anyone please advise me of what am I doing wrong here?
I am trying to construct the image URL but using the flickr.photos.search method
now (I need to display images close to geolocation of the visitor), I had it
working before with groups_pool.gne and the JSON feed was different (simpler)
formatted but now..
The URL is working, I get the array with all the data I need (farm, server,
secret and id) but can't construct the url for the photo.
$.getJSON("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_\
key=KEY&format=json&privacy_filter=0&media=photos&has_geo=1&accuracy=13&sort=int\
erestingness-desc&content_type=1&per_page=32&extras=geo,owner_name&page=1&radius\
_units=km&radius=1.521739&lat=40.952532&lon=-4.1326349999999366&text=Alcazar&jso\
ncallback=jsonp1320163051486", getJSONimages);
function getJSONimages(data) {
var htmlString = "";
$.each(data.photos.photo, function(i,item){
htmlString += '<img src="http://farm'+ item.farm +'.static.flickr.com/'+
item.server +'/'+ item.id +'_'+ item.secret +'_m.jpg" />';
});
$('#slideshow').html(htmlString);
Thank you.
I have added the url_m in the extras, in the URL to get the JSON feed and I get the full URL in my feed and that should help as I do not have to concatenate the rest but still doesn't work.
I can't get it to work, and it's extremely frustrating as I know is very simple.
Well, not for me obviously.
This is my function, after I get the url_m in the loop:
function getJSONimages(data) {
var htmlString = "";
$.each(data.photos.photo, function(i,item){
// var url = (item.url_m).replace("\", "");
htmlString += '<img src="' + item.url_m + '" />';
});
$('#slideshow').html(htmlString);
}
Even if I use the "url" variable or no, same result.
However, I have noticed something.
In the feed using groups_pool.gne, where I am able to pull the photos
successfully, I go to the media.m like that:
$.each(data.items, function(i,item){
var biggestSize = (item.media.m).replace("_m.jpg", ".jpg");
htmlString += '<img src="' + biggestSize + '" />';
Notice that I have items, then media, then m with it's own value! Is actually
items.[media: {m:PHOTOURL}].
Where as in this other JSON feed using the flickr.photos.search method, I have
the following "object path":
jsonFlickrApi.photos.photo[{url_m:PHOTOURL}]
And try to use this loop:
$.each(data.photos.photo, function(i,item){
htmlString += '<img src="' + item.url_m + '" />';
I think this is my problem but I don't have any ideas how to approach it. It's
obvious there is a different structure between the two feeds:
items.[media: {m:PHOTOURL}]
photos.photo[{url_m:PHOTOURL}]
I am going to research more on jQuery loops. Any ideas?
Weirdly these docs don't mention getting the farm. Can you console.log your item in the $.each loop and see what you get?
http://www.flickr.com/services/api/flickr.photos.search.html
It's clearly the right URL format though assuming you get all of those pieces:
http://www.flickr.com/services/api/misc.urls.html
EDIT
Can you tell me what this says (in the alert box):
$.each(data.photos.photo, function(i,item){
var url = 'http://farm'+ item.farm +'.static.flickr.com/' + item.server +'/'+ item.id +'_'+ item.secret +'_m.jpg';
alert(url);
});
A URL is not a JSON object so you cannot parse it.
You're trying get the URL parameters.
Include the following function and use it like this.
lat = querySt('lat');
lon = querySt('lon');
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
You might want to modify this part
hu =window.location.search.substring(1);
to
hu = yourURLVariable;
if you're getting the URL from somewhere else.