JavaScript error with XML when trying to read empty node - javascript

I am trying to render a catalog from an XML document and everything works, although when trying to show a default image if there is no image present in the XML node, it disables the parent node therefore forcing it not to show any of it and it reads me an error in my console saying:
Uncaught TypeError: Cannot read property 'getElementsByTagName' of
undefined
Which is pointing to this part of the code:
if (records[i].getElementsByTagName("IMAGE")[0].childNodes.length > 0)
{
So my question is where in my code below is my error causing it to not load the XML node?
PS: If anybody needs more of my code please let me know, and I would be happy to post it.
for (var i = fromItem; i < nextMaxItem; i++) {
if (records[i].getElementsByTagName("IMAGE")[0].childNodes.length > 0) {
xmlContent += '<article class="post all ' + records[i].getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue + '" id="">'
+ '<div class="col-sm-4 col-lg-4 col-md-4"><div class="thumbnail img-hover">'
+ '<a class="fancybox" rel="group" href="' + records[i].getElementsByTagName("BIGIMAGE")[0].childNodes[0].nodeValue + '" title="'+ records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue +'">'
+ '<img class="product-image" src="' + records[i].getElementsByTagName("IMAGE")[0].childNodes[0].nodeValue + '" alt="' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '" />'
+ '<div class="caption">'
+ '<h4>' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '</h4>'
+ '<p>' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '</p>'
+ '</div>'
+ "</a></div></div></article>";
} else {
xmlContent += '<article class="post all ' + records[i].getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue + '" id="">'
+ '<div class="col-sm-4 col-lg-4 col-md-4"><div class="thumbnail img-hover">'
+ '<a class="fancybox" rel="group" href="' + records[i].getElementsByTagName("BIGIMAGE")[0].childNodes[0].nodeValue + '" title="'+ records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue +'">'
+ '<img class="product-image" src="/images/Products/no-preview.jpg" alt="No Preview Available" />'
+ '<div class="caption">'
+ '<h4>' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '</h4>'
+ '<p>' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '</p>'
+ '</div>'
+ "</a></div></div></article>";
}
}
Here is the whole JavaScript code:
var page = 1, perPage = 12, content = document.getElementById('content'),
pagination = document.getElementById('pagination'), records;
function paganation(page) {
var nextMaxItem = perPage * page,
fromItem = (page - 1) * perPage,
maxPages = Math.ceil(records.length / perPage);
var xmlContent = '<div class="row">';
for (var i = fromItem; i < nextMaxItem; i++) {
if (records[i].getElementsByTagName("IMAGE")[0].childNodes.length > 0) {
xmlContent += '<article class="post all ' + records[i].getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue + '" id="">'
+ '<div class="col-sm-4 col-lg-4 col-md-4"><div class="thumbnail img-hover">'
+ '<a class="fancybox" rel="group" href="' + records[i].getElementsByTagName("BIGIMAGE")[0].childNodes[0].nodeValue + '" title="' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '">'
+ '<img class="product-image" src="' + records[i].getElementsByTagName("IMAGE")[0].childNodes[0].nodeValue + '" alt="' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '" />'
+ '<div class="caption">'
+ '<h4>' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '</h4>'
+ '<p>' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '</p>'
+ '</div>'
+ "</a></div></div></article>";
} else {
xmlContent += '<article class="post all ' + records[i].getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue + '" id="">'
+ '<div class="col-sm-4 col-lg-4 col-md-4"><div class="thumbnail img-hover">'
+ '<a class="fancybox" rel="group" href="' + records[i].getElementsByTagName("BIGIMAGE")[0].childNodes[0].nodeValue + '" title="' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '">'
+ '<img class="product-image" src="/images/Products/no-preview.jpg" alt="No Preview Available" />'
+ '<div class="caption">'
+ '<h4>' + records[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + '</h4>'
+ '<p>' + records[i].getElementsByTagName("SHORTDESCRIPTION")[0].childNodes[0].nodeValue + '</p>'
+ '</div>'
+ "</a></div></div></article>";
}
}
xmlContent += "</div>";
content.innerHTML = xmlContent;
var paginationContent = '<nav><ul class="pagination">';
if (page > 1) {
paginationContent += '<li>';
paginationContent += '<span aria-hidden="true">«</span>';
paginationContent += '</li>';
} else {
paginationContent += '<li class="disabled">';
paginationContent += '<span aria-hidden="true">«</span>';
paginationContent += '</li>'
}
var prevPosition = page - 3;
var nextPosition = page + 3;
for (var i = 1; i <= maxPages; i++) {
if (i != page) {
if (i >= prevPosition && i <= nextPosition) {
var linkToPage = i == prevPosition ? 1 : i == nextPosition ? maxPages : i;
var linkText = i == prevPosition ? "..." : i == nextPosition ? "..." : i;
paginationContent += "<li>";
paginationContent += '' + linkText + '';
paginationContent += "</li>";
}
} else {
paginationContent += "<li class='active'>";
paginationContent += '' + i + '';
paginationContent += "</li>";
}
}
var next = page + 1;
if (next <= maxPages) {
paginationContent += '<li>';
paginationContent += '<span aria-hidden="true">»</span>';
paginationContent += '</li>';
} else {
paginationContent += '<li class="disabled">';
paginationContent += '<span aria-hidden="true">»</span>';
paginationContent += '</li>';
}
paginationContent += '</ul></nav>';
pagination.innerHTML = paginationContent;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", xmlUrl, false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
records = xmlDoc.getElementsByTagName(xmlNode);
records = Array.prototype.slice.call(records).sort(function () {
return Math.random() > 0.5 ? 1 : -1
});
paganation(1);

If we imagine that records was of length 18, then for the second page, you would have:
fromItem - 12
nextMaxItem - 24
You are iterating i from fromItem to nextMaxItem, but as soon as you go past i = 18, you've gone past the end of records. You need to make sure that doesn't happen. You need to ensure that you don't iterate past the end of your array:
var max = Math.min(nextMaxItem, records.length);
for (var i = fromItem; i < max; i++) {
....
}

Related

appending not working and not showing error too

I am trying to call function.to open the popup to the screen.but it not show the pop up and not showing error too.function is calling properly tried print detail using console.log. Data is coming properly.i think some issue while appending the popup division.please help me out.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function viewCamp(id) {
$('#customModal').remove();
listable = "<h1 style='text-align: center;'>Camp Details<h1>";
$.get("camp-details-ajax.php?e2c=" + id, function(data) {
obj = $.parseJSON(data);
console.log(obj);
listable += "<table style='text-align:left'>";
listable += "<tr><th>Organization name</th><td>" + obj.CAMP_SCHOOL_NAME + "</td></tr>";
listable += "<tr><th>Name of contact person</th><td>" + obj.CAMP_SCHOOL_PRINCIPAL_NAME + "</td></tr>";
listable += "<tr><th>Mobile Number</th><td>" + obj.CAMP_SCHOOL_CONTACT_NUM + "</td></tr>";
if (obj.CAMP_SCHOOL_LANDLINE != '' && obj.CAMP_SCHOOL_LANDLINE != null) {
listable += "<tr><th>Landline Number</th><td>" + obj.CAMP_SCHOOL_STD_CODE + "-" + obj.CAMP_SCHOOL_LANDLINE + "</td></tr>";
}
listable += "<tr><th>Email</th><td>" + obj.CAMP_SCHOOL_EMAIL + "</td></tr>";
listable += "<tr><th>Address1</th><td>" + obj.CAMP_SCHOOL_ADD1 + "</td></tr>";
listable += "<tr><th>Address2</th><td>" + obj.CAMP_SCHOOL_ADD2 + "</td></tr>";
if (obj.CAMP_SCHOOL_ADD3 != '' && obj.CAMP_SCHOOL_ADD3 != null) {
listable += "<tr><th>Address3</th><td>" + obj.CAMP_SCHOOL_ADD3 + "</td></tr>";
}
listable += "<tr><th>City </th><td>" + obj.CAMP_SCHOOL_CITY + "</td></tr>";
listable += "<tr><th>State</th><td>" + obj.CAMP_SCHOOL_STATE + "</td></tr>";
listable += "<tr><th>Pincode</th><td>" + obj.CAMP_SCHOOL_PIN + "</td></tr>";
listable += "<tr><th>Doctor Name</th><td>" + obj.CAMP_TEMP_DENT_NAME + "</td></tr>";
listable += "<tr><th>Doctor Email</th><td>" + obj.CAMP_TEMP_DENT_EMAIL + "</td></tr>";
listable += "<tr><th>Doctor Mobile</th><td>" + obj.CAMP_TEMP_DENT_MOBILE + "</td></tr>";
listable += "<tr><th>Strength of Whole School/Organization</th><td>" + obj.CAMP_NO_OF_STUDENT + "</td></tr>";
listable += "<tr><th>Number of Students/Children attending</th><td>" + obj.CAMP_NO_OF_STU_ATTEND + "</td></tr>";
listable += "</table>";
$('body').append(' <div class="modal fade" id="customModal" role="dialog"><div class="modal-dialog"> <div class="modal-content"><div class="modal-body"><button type="button" class="close" data-dismiss="modal"><img src="images/close.png" class="img-responsive" width="100%" ></button><p>' + listable + '</p></div></div></div></div>');
});
}
$('body').on('click', '.close', function() {
$('#customModal').remove();
})
</script>

How do I get an ID from a click event handler?

I am trying to create an ID to use as a selector for a modal that I will then be able to access the display properties.
$.ajax({
url: 'https://randomuser.me/api/?results=12',
dataType: 'json',
success: function(data) {
console.log(data);
employees = data.results;
$.each(employees, function (i, employee) {
newHTML += '<div id="' + i + '" class="container">';
newHTML += '<div class="employee-img-container">';
newHTML += '<img class="employee-img" src="' + employee.picture.large + '" alt="employee image">';
newHTML += '</div>';
newHTML += '<div class="employee-info-container">';
newHTML += '<h3 class="employee-name">' + employee.name.first + ' ' + employee.name.last + '</h3>';
newHTML += '<p class="employee-email">' + employee.email + '</p>';
newHTML += '<p class="employee-location">' + employee.location.city + ', ' + employee.location.state + '</p>';
newHTML += '</div></div></div></div>';
employeeArr.push(employee);
modalHTML += '<div id="modal' + i + '" class="modal">';
modalHTML += '<div class="modal-content">';
modalHTML += '<div class="modal-header">';
modalHTML += '<span class="close">×</span>';
modalHTML += '<img class="employee-img" src="' + employee.picture.large + '" alt="employee image">';
modalHTML += '<h2 class= emp-modal-name>' + employee.name.first + ' ' + employee.name.last + '</h2>';
modalHTML += '</div';
modalHTML += '<div class="modal-body">';
modalHTML += '<p>Employee Info</p>';
modalHTML += '</div></div></div>';
modalArr.push(employee);
});
$('.grid-container').html(newHTML);
$('.modal-container').html(modalHTML);
$('.container').on('click', function (event) {
console.log(event.currentTarget.id);
let newId = '#modal' + event.currentTarget.id;
let displayModal = $(newId)
let display = document.querySelector(newId);
//displayModal.style.display = 'block';
console.log(displayModal);
console.log(display);
console.log(newId);
});
}
});
When I log the event.currentTarget.id I get a number, and I can also create a string that I want to use as a selector. I can't figure out how to use it as the actual sector though. Not sure if I need to use an if statement to compare it to the id of the modal class that i want to display. Thanks!
Try like this
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id);
});
});

Duplicate item appearing in DIV

I have a problem with my code. I am pushing items into a new array and displaying two of them in a DIV. For some reason its showing the same item twice rather than showing two separate items. Hoping someone can help me out with this. I just need a way to prevent the same recipe from being able to show twice in the DIV.
var categoryItems = [];
var recipeTitle = $('#recipeTitle').text();
$.each(recipe_data, function(i, item){
if (item.recipeCategory == "4" && recipeTitle !== item.recipeName) { categoryItems.push(item); }
});
var similarRecipe = '';
var randomRecipe = {};
randomRecipe = categoryItems[Math.floor(Math.random()*categoryItems.length)];
for(var i = 0; i < categoryItems.length; i += 2) {
similarRecipe = [ '<div class="col-md-6 col-sm-6 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + randomRecipe.recipePageURL +'" data-title="' + randomRecipe.recipeName + '"></div>'
+ '' + '<img class="img-responsive" src="' + randomRecipe.recipeImageCategoryURL + '">' + ''
+ '' + '<h3 class="recipeSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>' ];
$('#recipeSimilar').append(similarRecipe);
}
Edit: Please take a look at this fiddle for an example. It should not show the same recipe twice when refreshing, rather show two different recipes from the category. My problem is that is is sometimes it is showing the same one twice when you refresh. https://jsfiddle.net/wn4fmm5r/
you are generating one random Recipe and displaying same twice into your for loop
randomRecipe = categoryItems[Math.floor(Math.random()*categoryItems.length)];
for(var i = 0; i < categoryItems.length; i += 2) {
similarRecipe = [ '<div class="col-md-6 col-sm-6 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + randomRecipe.recipePageURL +'" data-title="' + randomRecipe.recipeName + '"></div>'
+ '' + '<img class="img-responsive" src="' + randomRecipe.recipeImageCategoryURL + '">' + ''
+ '' + '<h3 class="recipeSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>' ];
$('#recipeSimilar').append(similarRecipe);
}
try including your statement for generating random recipe inside loop.
for(var i = 0; i < categoryItems.length; i += 2) {
randomRecipe = categoryItems[Math.floor(Math.random()*categoryItems.length)];
similarRecipe = [ '<div class="col-md-6 col-sm-6 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + randomRecipe.recipePageURL +'" data-title="' + randomRecipe.recipeName + '"></div>'
+ '' + '<img class="img-responsive" src="' + randomRecipe.recipeImageCategoryURL + '">' + ''
+ '' + '<h3 class="recipeSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>' ];
$('#recipeSimilar').append(similarRecipe);
}
Edit for no repeating ----
var counter;
for (var i = 0; i < categoryItems.length; i += 2) {
var item = Math.floor(Math.random() * categoryItems.length);
if (!counter) {
counter = item;
} else {
if (counter == item) {
item = Math.floor(Math.random() * categoryItems.length);
counter = item;
}
}
randomRecipe = categoryItems[item];
similarRecipe = ['<div class="col-md-6 col-sm-6 img-margin">' + ' <div class="addthis_inline_share_toolbox" data-url="' + randomRecipe.recipePageURL + '" data-title="' + randomRecipe.recipeName + '"></div>'
+ '' + '<img class="img-responsive" src="' + randomRecipe.recipeImageCategoryURL + '">' + ''
+ '' + '<h3 class="recipeSubCategoryImgCaption">' + randomRecipe.recipeName + '</h3>' + '' + '</div>'];
$('#recipeSimilar').append(similarRecipe);
}

I'd like to reference a button status within a script

How can I reference my menu button from my script? When I click the button after implementation, it doesn't seem to hold true... Thank you for your help! The problem here is specifically directed towards the if statement in the bottom script where it states if(data_type ==1){ do something}.
var data_type = 0;
function data() {
data_type = 1;
}
///menu-button///
<li id="menu" onclick="data()" style="max-width:82px">
DATA
</li>
<script>
document.write('<div id="div2" class="wrapper">');
document.write('<ul id="Grid">');
for (var i = 0; i < 33; i++) {
var ch = "";
if (i%3==0) { ch="E"; } else if (i%3==1) { ch="C"; } else { ch="W"; }
document.write('<li id="mE'+ i + '" class="mix ' + sortSettings[i][0] + ' ' + i
+ '" onclick="imgClicked(' + i + ')" > <div class="content"> <div><img class="bImg" id="imgI' + i
+ '" src="ico1.jpg" width="145" height="213"></div> <div id="menu"> <img id="gI' + i + '" src="ico1.jpg" width="35" height="35" style="float:left"></div>'
+ '<div id="descNum">' + (Math.floor(i/3)+1) + ch + '</div>'
+ '<div id="desc">' + allSettings[i][1] + '</div>'
+ '<div id="desc">' + allSettings[i][2] + '</div>'
+ '<div id="desc">' + allSettings[i][0] +' '+ allSettings[i][3] + '</div></div></li>');
}
for (var i = 0; i < 11; i++) {
for (var j = 0; j < 3; j++) {
var add = "";
if(data_type == 1){
if (j==0) {
add="E";
$("#imgI" + ((i*3)+j)).attr("src", "Beds/20160530/" + (i+1) + add + "(1).JPG");
} else if (j==1) {
add="C";
$("#imgI" + ((i*3)+j)).attr("src", "Beds/20160530/" + (i+1) + add + "(1).JPG");
} else if (j==2) {
add="W";
$("#imgI" + ((i*3)+j)).attr("src", "Beds/20160530/" + (i+1) + add + "(1).JPG");
}
}
else{
if (j==0) {
add="E";
$("#imgI" + ((i*3)+j)).attr("src", "Beds/20160530/" + (i+1) + add + ".JPG");
} else if (j==1) {
add="C";
$("#imgI" + ((i*3)+j)).attr("src", "Beds/20160530/" + (i+1) + add + ".JPG");
} else if (j==2) {
add="W";
$("#imgI" + ((i*3)+j)).attr("src", "Beds/20160530/" + (i+1) + add + ".JPG");
}
}
}
}
document.write('<li class="gap"></li>');
document.write('</ul>');
document.write('</div>');
</script>

Need help with Flickr/JSON/Javascript issue when displaying gallery images

Wondering if anyone can help me. I'm trying to put together a weekly photo competition page by pulling in photos from a Flickr gallery, but I can't get the images to display. It works OK for groups, but having some problems with the gallery code. Getting the correct JSON response, but can't get the results to display on the page as good as the group images do.
Here's my Javascript:
$(function() {
var map;
var markers = [];
var infowindow;
// Get gallery photos
var visibleGallery;
$.getJSON("http://api.flickr.com/services/rest/" +
"?method=flickr.galleries.getPhotos" +
"&api_key=XXXX" +
"&photoset_id=XXXX" +
"&extras=geo,tags,url_sq,url_t,url_s,url_m,url_o" +
"&format=json&jsoncallback=?", function(data, textStatus) {
var htmlString = '<div id="weekContainer">';
var weeks = sortIntoWeekArrays(data.photos.photo);
$.each(weeks, function(i, week)
{
var weekNumber = i + 1;
var numberOfWeeks = weeks.length - 1;
htmlString += '<div id="week' + weekNumber + '">';
htmlString += '<ul class="weeks">';
if(i < numberOfWeeks)
{
htmlString += '<li><a class="weekLinksNext" href="#"><span>Next</span></a></li>';
}
var sunday = new Date(week.monday.toUTCString());
sunday.setDate(week.monday.getDate() + 6);
htmlString += '<li class="weekTitle">Week ' + weekNumber + ':</li><li class="weekDate"> ' + week.monday.format("ddd d mmm") + ' — ' + sunday.format("ddd d mmm") + '</li>';
if(i > 0)
{
htmlString += '<li><a class="weekLinksPrev" href="#"><span>Previous</span></a></li>';
}
htmlString += '</ul>';
if(week.winner !== undefined)
{
htmlString += '<p class="galleryTitleFirst">Photo of the Week</p>';
htmlString += '<ul class="imagesWinners">';
htmlString += '<li class="winner"><a href="http://www.flickr.com/photos/' + week.winner.owner + '/' + week.winner.id + '" target="_blank">';
htmlString += '<img title="' + week.winner.title + '" src="' + week.winner.url_m + '" alt="' + week.winner.title + '" />';
htmlString += '</a></li>';
htmlString += '<li class="name">' + week.winner.title + '</li>';
htmlString += '<li class="owner">' + 'by ' + week.winner.ownername + '</li>';
htmlString += '</ul>';
}
htmlString += '<p class="galleryTitle">Our other favourites this week</p>';
htmlString += '<ul class="imagesRunnersUp">';
$.each(week.images, function(i, item)
{
htmlString += '<li><a href="http://www.flickr.com/photos/' + item.owner + '/' + item.id + '" target="_blank">';
htmlString += '<img title="' + item.title + '" src="' + item.url_sq + '" alt="' + item.title + '" />';
htmlString += '</a></li>';
if(item.longitude == "0" && item.latitude == "0")
{
return true;
}
var latlng = new google.maps.LatLng(item.latitude, item.longitude);
var marker = new google.maps.Marker(
{
position: latlng,
map: map,
title:item.title
});
marker.content = '<img title="' + item.title + '" src="' + item.url_s + '" alt="' + item.title + '" />';
markers.push(marker);
});
htmlString += '</ul>';
htmlString += '</div>';
});
htmlString += '</div>';
$('div#weekViewer').append(htmlString);
$('div#weekContainer > div').css('float', 'left').css('margin-right', '30px');
$('div#weekContainer').width(weeks.length * 450);
$('div#weekContainer .weekLinksPrev')
.click(function(){
$('div#weekViewer').animate({scrollLeft: '-=450'}, 'slow');
return false;
});
$('div#weekContainer .weekLinksNext')
.click(function(){
$('div#weekViewer').animate({scrollLeft: '+=450'}, 'slow');
return false;
});
});
});
function sortIntoWeekArrays(items)
{
var weeks = [];
// Returns single dimension array containing single dimension arrays
$(items).each(function(i, item)
{
var monday = new Date(item.dateadded * 1000);
monday.setDate(monday.getDate() - monday.getDay() + 1);
monday.setHours(0,0,0,0);
var week, thisWeek;
for (i in weeks)
{
week = weeks[i];
if(week.monday - monday == 0)
{
thisWeek = week;
break;
}
}
if(thisWeek === undefined)
{
thisWeek =
{
monday: monday,
images: []
};
weeks.push(thisWeek);
}
if($.inArray('winner', item.tags.split(" ")) > -1)
{
thisWeek.winner = item;
}
else
{
thisWeek.images.push(item);
}
});
return weeks.sort(function(first, second)
{
return (first.monday > second.monday) - (first.monday < second.monday);
});
}
Any help would be fantastic :)
Regards,
David
Worked it out after some help from a friend. I was missing the date_upload value in the extras argument and item.dateadded needed to change to item.upload.

Categories

Resources