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
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 = "";
As I need to bring separate data from a php file, and create an HTML piece to be injected with jQuery, I've choosen Json.
I send it from my PHP main file (between script tags) like this:
$.ajax({dataType: "json", url:'course_generator.php', data:{co_subj_co:editedCourseId}}).done(function(newCourse){
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow" data-isMultisubjectValue="'+isMultisubjectValue+'" data-subjectsNum="'+subjectsNum+'" data-id="'+courseId+'" id="'+courseId+'" data-abbrev="'+newCourseAbbrev+'" data-courseTypeId="'+newCourseTypeId+'" title="'+newCourseName+'"><div class="contentColumn40"><span class="tableContentText">'+newCourseName+' ('+newCourseTypeName+')</span></div><div class="contentColumn40">'+subjectList+'</div><div class="contentColumn10"><div class="tableIconLink"><div class="editIcon" data-id="'+courseId+'" title="Editar '+newCourseName+'"></div></div></div><div class="contentColumn10"><div class="tableIconLink"><div data-id="'+courseId+'" class="discontinueIcon" title="Discontinuar '+newCourseName+'"></div></div></div></div>';}
This sends properly editedCourseId value. And what's inside course_generator.php is:
$courseId = $_POST['co_subj_co'];
$select_co = mysql_query("SELECT * FROM course_conf JOIN course_type ON co_fk_ct_id=ct_id JOIN co_rel_subj ON co_subj_co='$courseId' JOIN subject_conf ON su_id=co_subj_subj WHERE co_id='$courseId'");
$result_co = mysql_fetch_array($select_co);
$newCourseId = $result_co['co_id'];
$newCourseName = $result_co['co_name'];
$newCourseAbbrev = $result_co['co_abbrev'];
$newCourseTypeId = $result_co['co_fk_ct_id'];
$newCourseTypeName = $result_co['ct_name'];
$isMultisubjectValue = $result_co['co_multisubject'];
$newCourseValues = '{"newCourseId":'.$newCourseId.',"newCourseName":'.$newCourseName.',"newCourseAbbrev":'.$newCourseAbbrev.',"newCourseTypeId":'.$newCourseTypeId.',"newCourseTypeName":'.$newCourseTypeName.',"isMultisubjectValue":'.$isMultisubjectValue.'}';
I am afraid Im not receiving it properly by $courseId = $_POST['co_subj_co'];, and neither $newCourseValues are being received properly on my main PHP file as my newCourseStructure is not generating anything. Could you please identify the several errors I am sure I'm making? Thank you.
UPDATE:
After changing my PHP main file to:
$.ajax({type : 'POST', dataType: "json", url:'config/forms/course_conf/course_generator.php', data:{co_subj_co:editedCourseId}}).done(function(newCourse){
var courseId = newCourse.newCourseId;
var newcourseName = newCourse.newCourseName;
var isMultisubjectValue = newCourse.isMultisubjectValue;
var subjectsNum = newCourse.subjectsNum;
var newCourseAbbrev = newCourse.newCourseAbbrev;
var newCourseTypeId = newCourse.newCourseTypeId;
var newCourseTypeName = newCourse.newCourseTypeName;
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow" data-isMultisubjectValue="'+isMultisubjectValue+'" data-subjectsNum="'+subjectsNum+'" data-id="'+courseId+'" id="'+courseId+'" data-abbrev="'+newCourseAbbrev+'" data-courseTypeId="'+newCourseTypeId+'" title="'+newCourseName+'"><div class="contentColumn40"><span class="tableContentText">'+newCourseName+' ('+newCourseTypeName+')</span></div><div class="contentColumn40">'+subjectList+'</div><div class="contentColumn10"><div class="tableIconLink"><div class="editIcon" data-id="'+courseId+'" title="Editar '+newCourseName+'"></div></div></div><div class="contentColumn10"><div class="tableIconLink"><div data-id="'+courseId+'" class="discontinueIcon" title="Discontinuar '+newCourseName+'"></div></div></div></div>';}
And my course_generator.php file to:
$courseId = intval($_POST['co_subj_co']);
$subjectList = "";
$data ="";
$select_co = mysql_query("SELECT * FROM course_conf JOIN course_type ON co_fk_ct_id=ct_id JOIN co_rel_subj ON co_subj_co='$courseId' JOIN subject_conf ON su_id=co_subj_subj WHERE co_id='$courseId'");
$result_co = mysql_fetch_array($select_co);
$outArr['newCourseId'] = $result_co['co_id'];
$outArr['newCourseName'] = $result_co['co_name'];
$outArr['newCourseAbbrev'] = $result_co['co_abbrev'];
$outArr['newCourseTypeId'] = $result_co['co_fk_ct_id'];
$outArr['newCourseTypeName'] = $result_co['ct_name'];
$outArr['isMultisubjectValue'] = $result_co['co_multisubject'];
$subjectsNum=mysql_num_rows(mysql_query("SELECT * FROM co_rel_subj WHERE co_subj_co = '$courseId'"));
$outArr['subjectsNum'] = $subjectsNum;
echo json_encode($outArr);
Instead of showing the HTML piece structured, this is what $newCourseStructure results:
{"newCourseId":"243","newCourseName":"a","newCourseAbbrev":"ae","newCourseTypeId":"1","newCourseTypeName":"M\u00e1ster","isMultisubjectValue":"1","subjectList":"
Edici\u00f3n y Acabado de Imagen Digital<\/div>
","subjectsNum":1}
Your JSON string is not valid JSON because you don't use quotes around the string values. Instead of manually creating JSON, create an array or object and then json_encode() it.
You don't apper to output the JSON string. Use echo or print.
Add dataType : 'json' to your ajax request so that jQuery will parse the JSON, returning the native JavaScript object. All of the variables you use in the success function are undefined. After parsing the JSON you should use
var courseId = newCourse.newCourseId; // and so on
Your ajax request doesn't have a type and so will default to GET. add type : 'POST' if you want to use POST.
Try $_GET['co_subj_co']; instead of POST.
As long as you don't specify the method to jQuery's ajax call, it's made by GET, not POST.
I have annotated two things in the code:
$.ajax({
type : 'POST',
dataType: "json",
url:'config/forms/course_conf/course_generator.php',
data:{
co_subj_co:editedCourseId
}})
.done(function(newCourse){
var courseId = newCourse.newCourseId;
var newcourseName = newCourse.newCourseName;
var isMultisubjectValue = newCourse.isMultisubjectValue;
var subjectsNum = newCourse.subjectsNum;
var newCourseAbbrev = newCourse.newCourseAbbrev;
var newCourseTypeId = newCourse.newCourseTypeId;
var newCourseTypeName = newCourse.newCourseTypeName;
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow"'
+ ' data-isMultisubjectValue="' + isMultisubjectValue + '"'
+ ' data-subjectsNum="' + subjectsNum + '"'
+ ' data-id="' + courseId + '"'
+ ' id="' + courseId + '"'
+ ' data-abbrev="' + newCourseAbbrev + '"'
+ ' data-courseTypeId="' + newCourseTypeId + '"'
+ ' title="' + newCourseName + '">'
+ '<div class="contentColumn40"><span class="tableContentText">'
+ newCourseName + ' (' + newCourseTypeName + ')</span></div>'
// WHERE IS subjectList DEFINED?
+ '<div class="contentColumn40">' + subjectList
+ '</div>'
+ '<div class="contentColumn10"><div class="tableIconLink">'
+ '<a href="#"><div class="editIcon" data-id="' + courseId + '"'
+ ' title="Editar ' + newCourseName + '"></div>'
+ '</a></div></div><div class="contentColumn10"><div class="tableIconLink">'
+ '<a href="#"><div data-id="'+courseId+'" class="discontinueIcon" '
+ 'title="Discontinuar '+newCourseName+'"></div></a></div></div></div>';
/*
* your HTML is generated, but you never put it in the DOM
*/
$('#idOutputWrapper').empty().html(newCourseStructure);
}
When you use subjectList from the json response, please notice that it comes with a closing </div> tag for some reason, maybe you should change that, too.
btw: Your code formatting is horrible, sorry to say so. You can compress your js before uploading it to the server, but while working on it, it NEEDS to be readable. I just edited it to fit better in the codeblock here.
Are you actually using POST, or are you firing off a GET request (your browser's developer tools should tell you this easily). You should also make sure that $courseId is an integer by $courseId = intval($_POST['co_cubj_co']);. In addition, you should add a condition for the event that the requested ID is not found.
As MueR suggests, the reason to make sure that courseID is an integer is to prevent SQL injection (unless you want people to do things like delete your entire DB at will). This, of course, assumes that courseID is something like an autoincrement int.
However, you've got a number of other problems. Your JSON is invalid since you're ostensibly writing out unquoted strings... you should just use json_encode:
$outArr = array();
$outArr['newCourseId'] = $result_co['co_id'];
$outArr['newCourseName'] = $result_co['co_name'];
...
echo json_encode($outArr);
Personally, I prefer to just use $_REQUEST, which concatenates both $_POST and $_GET. Makes it easier.
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
Messing around for days know. Learning javascript and jquery a few weeks, it goes well, but sometimes...
For an mobile app i'm trying to get the coordinates. Showing them on page isn't a problem, but I want them elsewhere.
In the main.js
var getLocation = function() {
var suc = function(p) {
document.getElementById("locatie").innerHTML = "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20";
};
var locFail = function() {
};
navigator.geolocation.getCurrentPosition(suc, locFail);
};
And in the htmlfile
<body onload="getLocation();" >
<p id="locatie">Finding geolocation...</p></ul>
<div id="geolocation">
Bezig met laden. Momentje geduld</div>
<script type="text/javascript">
jQuery(function(){
var script=document.createElement('script');
script.type='text/javascript';
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
$("body").append(script);
});
function processTheseTerraces(jsonData){
var shtml = '';
var results = jsonData.results;
if(results){
$.each(results, function(index,value){
shtml += "<li class='store'><a class='noeffect' href='#'><span class='image' style='background-image: url(pics/terras1.jpg)'></span><span class='comment'>" + value.address + "</span><span class='name'>" + value.building_name + "</span><span class='stars5'></span><span class='starcomment'>132 Beoordelingen</span><span class='arrow'></span></a></li>";
});
$("#geolocation").html( shtml );
}
}
</script>
Now I want the coordinates passing through json and load the data. I thought to change
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
in
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20";
But that doesn't work. Anyone suggestions how I can solve this.
This: http://www.192.168.1.111 is just a wrong URL. I guess you need just this: http://192.168.1.111
Geolocation can take a long time (multiple seconds). It is an asynchronous request which means that the other javascript code may execute before the geolocation has grabbed the address. The solution is to put any code or function calls that use the location inside the callback function on the navigator.geolocation.getCurrentPosition
The JQuery is building the URL before the lat and lng have been defined.
onload="getLocation();" tells that when the document is loaded call getLocation function and inside this function you set the innerHTML of <P id="locatie"> TAG as: http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20
So problems are:
If you make a script tag and assign source then browser fetch the source data but writing an url on inner html of a <p> tag won't do this and it doesn't make sense.
Code fragment below is loaded before the document is loaded but i guess you do not want this:
jQuery(function(){
var script=document.createElement('script');
script.type='text/javascript';
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
$("body").append(script);
});
If you want: script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20"; then you have to define p.coords first and before calling this otherwise p.coords is undefined.
Solution i am not sure what you exactly asking so could not answer. Do you want to assign inner HTML of the #locatie element or do you want to load customized script as tag?
Either ways, you have to make an ajax call to server which maybe like this:
$.ajax({
url: "http://www.192.168.1.111/tools/gpslocation.php",
data: "lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20",
success: function(Result){
// use Result variable in came from the success function.
document.getElementById("Your_ID_Goes_Here").innerHTML = "do_Something";
}
});