Displaying favico image from database to html using javascript shows "undefined" - javascript

I have read a lot of similar examples here on S.O yet, I cannot figure out what is the problem. The item.picture image is successfully displayed on the html and its url can also be printed on the console.
However, the favico displays undefined both on the console and on html.
Here is the sample code:
$(function () {
jQuery.ajax({
type:'GET',
url:"api/wedding/?format=json&limit=20",
dataType:"json",
success :function (data) {
var listA=$("#wedding_id");
for(var i=0;i<data.results.length;i++) {
var item=newDiv(data.results[i])
listA.append(item);
}
},
error:function (e) {
console.log(e) // Better for debugging
// alert("Error" + e)
}
});
});
function newDiv(item)
{
if (item.pic) {
var wed_pic = item.pic.split(",")[0];
}
if (item.favico) {
var favicon = item.favico.split("/")[0];
}
console.log(item.pic); // <--- can display the pic_url on console
console.log(favicon); //shows 'undefined'
var template = '<ul class="wedding-list" id='+ item.wedding_id +'>'
+ '<a class="wedding-icon" href="#">' + favicon + '</a>' //<--- where I think lies the problem
+ '<a class="wed_img" target="_blank" href=' + item.url + '>'
+ '<img src=' + wed_pic + '>'
+ '</a> </ul>' +
return template
}
What could possibly be the cause of the undefined error? Thank you for helping.

for a start
const listA = document.querySelector('#wedding_id')
;
fetch ('api/wedding/?format=json&limit')
.then (res => res.json())
.then (data =>
{
for (let row of data.results)
listA.appendChild( newDiv(row))
})
.catch (err => console.error(err))
;
function newDiv(item)
{
let
e_UL = document.createElement('ul')
, wed_pic = !!item?.pic ? item.pic.split(',')[0] : ''
, favicon = !!item?.favico ? item.favico.split('/')[0] : ''
;
console.log('item ----->', JSON.stringify(item,0,2) )
console.log('wed_pic ->', wed_pic )
console.log('favicon ->', favicon )
e_UL.id = item.wedding_id
e_UL.className = 'wedding-list'
e_UL.innerHTML = `
<a class="wedding-icon" href="#"> ${favicon} </a>
<a class="wed_img" target="_blank" href="${item.url}">
<img src="${wed_pic}">
</a>`
return e_UL
}

Related

Displaying information from a JSON on map using wrong method?

I'm working through a project to show information from a third party api on a map.
I'm not very experienced figuring out what the console is telling me so I'm a little stuck on the error I'm getting. I've declared all the variables outside of the function so result is defined and all of these functions are aspects of a foursquare venue.
Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined
$.ajax({
url:'https://api.foursquare.com/v2/venues/search',
dataType: 'json',
data: 'limit=1' +
'&ll='+ placeItem.lat() +','+ placeItem.lng() +
'&client_id='+ CLIENT_ID +
'&client_secret='+ CLIENT_SECRET +
'&v=20140806' +
'&m=foursquare',
async: true,
success: function (data) {
result = data.response.venue;
contact = result.hasOwnProperty('contact') ? result.contact : '';
if (contact.hasOwnProperty('formattedPhone')) {
placeItem.phone(contact.formattedPhone || '');
}
location = result.hasOwnProperty('location') ? result.location : '';
if (location.hasOwnProperty('address')) {
placeItem.address(location.address || '');
}
bestPhoto = result.hasOwnProperty('bestPhoto') ? result.bestPhoto : '';
if (bestPhoto.hasOwnProperty('prefix')) {
placeItem.photoPrefix(bestPhoto.prefix || '');
}
if (bestPhoto.hasOwnProperty('suffix')) {
placeItem.photoSuffix(bestPhoto.suffix || '');
}
description = result.hasOwnProperty('description') ? result.description : '';
placeItem.description(description || '');
rating = result.hasOwnProperty('rating') ? result.rating : '';
placeItem.rating(rating || 'none');
url = result.hasOwnProperty('url') ? result.url : '';
placeItem.url(url || '');
placeItem.canonicalUrl(result.canonicalUrl);
// Infowindow code is in the success function so that the error message
// Content of the infowindow
contentString = '<div id="iWindow"><h4>' + placeItem.name() + '</h4><div id="pic"><img src="' +
placeItem.photoPrefix() + '110x110' + placeItem.photoSuffix() +
'" alt="Image Location"></div><p>Information from Foursquare:</p><p>' +
placeItem.phone() + '</p><p>' + placeItem.address() + '</p><p>' +
placeItem.description() + '</p><p>Rating: ' + placeItem.rating() +
'</p><p><a href=' + placeItem.url() + '>' + placeItem.url() +
'</a></p><p><a target="_blank" href=' + placeItem.canonicalUrl() +
'>Foursquare Page</a></p><p><a target="_blank" href=https://www.google.com/maps/dir/Current+Location/' +
placeItem.lat() + ',' + placeItem.lng() + '>Directions</a></p></div>';
// Add infowindows
google.maps.event.addListener(placeItem.marker, 'click', function () {
infowindow.open(map, this);
// Bounce animation
placeItem.marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
placeItem.marker.setAnimation(null);
}, 800);
infowindow.setContent(contentString);
});
},
// Alert the user on error.
error: function (e) {
infowindow.setContent('<h5>Foursquare data is unavailable.</h5>');
document.getElementById("error").innerHTML = "<h4>Foursquare data is unavailable. Please try refreshing.</h4>";
}
});
Not sure what data the call you are making is supposed to return but the error you are getting indicates that you did not get the data you were expecting.
result = data.response.venue;
"venue" is not a defined property of data.response so when you try and access result.hasOwnProperty('contact') it has no idea what to return since result is not defined.

JQuery Ajax button isn't working

I am extremely new at writing ajax and working with a restful api... so, bear with me.
I have a Laravel 5.2 RESTful API that I am using on the backend, and I'm attempting to simply load a list of categories using Jquery / Ajax. As you click through the categories, each child category loads fine, but I cannot seem to get the "back" button to work (by this, I mean the LI I am generating, not the browser back button). When you click it, it shows the alert - and the data is correct, but that's it. The list doesn't refresh and populate with the appropriate items.
EDIT
There are no errors being thrown to the javascript console either. It just won't populate from the ajax call.
EDIT
I removed the request.abort() right after I made the original post.
EDIT
Here is the JSON returned from the URL api/categories/4 - as an example.
[{"id":6,"parent":4,"name":"sub_subcat4_1","slug":"sub_subcat4_1","description":null,"created_at":null,"updated_at":null},{"id":7,"parent":4,"name":"sub_subcat4_2","slug":"sub_subcat4_2","description":null,"created_at":null,"updated_at":null}]
EDIT
Here is the HTML for the #categories
<div class="row">
<div class="col-sm-12">
<ul id="categories">
</ul>
</div>
The Javascript
<script>
/*
* This loads the default / root categories.
*/
function getRootCategories() {
$.getJSON("api/categories", function(data) {
var categories = [];
$("#categories").html("");
$.each(data, function(key, val) {
$("#categories").append("<li class='subcat' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>');
});
});
}
/*
* This loads the sub categories if there's any data returned. Otherwise, just leave the user where they are.
*/
function getSubcats(cat) {
var dataID = cat.getAttribute("data-id");
alert(dataID);
if(dataID == "null") {
getRootCategories();
}
else {
$.getJSON("api/categories/" + dataID, function (data) {
if (data.length != 0) {
$("#categories").html("");
var newCats = '';
var parent = '';
$.each(data, function (key, val) {
parent = "<li class='subcat' data-id='" + val.parent + "' onClick='getSubcats(this);'>Back</li>";
newCats += "<li class='subcat' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>';
});
$("#categories").append(parent + newCats);
}
});
}
}
$(document).ready(function() {
$.ajaxSetup({ cache:false });
getRootCategories();
});
</script>
Ok, I just had my variables all mixed up. I wasn't setting the correct parent id.
The new script looks like this -
<script>
var previous = null;
/*
* This loads the default / root categories.
*/
function getRootCategories() {
$.getJSON("api/categories", function(data) {
var categories = [];
$("#categories").html("");
$.each(data, function(key, val) {
$("#categories").append("<li class='subcat' data-parent='" + val.parent + "' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>');
previous = val.parent;
});
});
}
/*
* This loads the sub categories if there's any data returned. Otherwise, just leave the user where they are.
*/
function getSubcats(cat) {
var dataID = cat.getAttribute("data-id");
previous = cat.getAttribute("data-parent");
if(dataID == "null") {
getRootCategories();
}
else {
$.getJSON("api/categories/" + dataID, function (data) {
if (data.length != 0) {
$("#categories").html("");
var newCats = '';
var parent = '';
$.each(data, function (key, val) {
parent = "<li class='subcat' data-id='" + previous + "' onClick='getSubcats(this);'>Back</li>";
newCats += "<li class='subcat' data-parent='" + val.parent + "' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>';
});
$("#categories").append(parent + newCats);
}
})
.fail(function(jqxhr, textStatus, error) {
console.log("Request Failed: " + textStatus + " - " + error);
});
}
}
$(document).ready(function() {
$.ajaxSetup({ cache:false });
getRootCategories();
});
</script>

PHP,Jquery(ajax) post uncaught syntaxerror:unexpected token <

guys i keep on getting this uncaught syntaxerror:unexpected token <, and it points to the jquery library file,i am making a request to AJAX(comment-insert-ajax.php) using JQuery(comment-insert.js),i try removing the closing token of php(?>) in the AJAX script but i still get the error.I actually get the error when i add the 'require_once' lines,sorry about that.
comment-insert-ajax.php
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-insert')
{
$userId = (int)$_POST['userId'];
$comment = addslashes(str_replace("\n","<br>",$_POST['comment']));
$std = new stdClass();
$std->comment_id = 24;
$std->userId = $userId;
$std->comment = $comment;
$std->userName = "Thabo Ambrose";
$std->profile_img= "images/tbo.jpg";
require_once $_SERVER['DOCUMENT_ROOT'] . 'defines.php';
require_once MODELS_DIR . 'Comments.php';
echo json_encode($std);
}
else
{
header('location: /');
}
and following is the Jquery file that makes the request using the '$.post' method.
comment-insert.js
$(document).ready(function(){
$('#comment-post-btn').click(function(){
comment_post_btn_click();
});
});
function comment_post_btn_click()
{
var _comment = $('#comment-post-text').val();
var _userId = $('#user-id').val();
var _userName = $('#user-name').val();
if(_comment.length > 0 && _userId != null)
{
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(jQuery.parseJSON(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
else
{
//do something
$('#comment-post-text').addClass('alert alert-danger');
$('#comment-post-text').focus(function(){$('#comment-post-text').removeClass('alert alert-danger');});
}
//remove text in the text area after posting
$('#comment-post-text').val("");
}
function comment_insert(data)
{
var t = '';
t += '<li class="comment-holder" id="_'+data.comment_id+'">';
t += '<div class="user-img">';
t += '<img src="'+data.profile_img+'" class="user-img-pic">';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field">'+data.userName+'</h3>';
t += '<div class="comment-text">'+data.comment+'</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">x</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}
The error points to line 7497 of the jQuery library,it point to the following code
jQuery.parseJSON = function(data)
{
return data;
}
Try using the JSON.parse function:
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(JSON.parse(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
try puting the data in a array and then encode it
$array = ['comment_id' => 24,'userId' => $userId,'comment' => $comment,'userName' => "Thabo Ambrose",'profile_img'= "images/tbo.jpg"];
echo json_encode($array);
change if(isset($_POST['task']) && $_POST['task'] == 'comment-insert') this line of code to if(isset($_POST['task']) && isset($_POST['task'])&&$_POST['task']== 'comment-insert').
then change the ajax call to
$.ajax({
url: "ajax/comment-insert-ajax.php",
data :{"task":"comment-insert","UserId":_userId,"comment":_comment},
type: "POST",
dataType: "json",
success:function(msg) {
}
});

Uncaught TypeError: Cannot set property '0' of undefined

I am using Facebooks Javascript API to import to my website the albums and photos of a Facebook page.
My javascript code looks like this :
<script>
var albumPhotos = new Array();
var albumThumbnails = new Array();
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '5698434687426', // App ID from the app dashboard
channelUrl : 'channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
FB.api('1607099163/albums', function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
// render photos
for(var i=0; i<response.data.length; i++){
(function (i) {
var albumName = response.data[i].name;
var albumCover = response.data[i].cover_photo;
var albumId = response.data[i].id;
var numberOfPhotos = response.data[i].count
FB.api(albumId + "/photos", function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
for(var k=0; k<numberOfPhotos; k++){
albumThumbnails[i][k] = response.data[k].picture;
albumPhotos[i][k] = response.data[k].source;
}
}
});
console.log(albumName);
FB.api( albumCover, function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
// render photos
$(".albums").append('<li>'+
'<a href="#Gallery' + i + '"' + 'data-transition="slidedown">'+
'<img src= "' + response.picture + '" />'+
'<h2>' + albumName + '</h2>'+
'<p>' + "Number of Photos: " + numberOfPhotos +'</p>'+
'</a>'+
'</li>')
.listview('refresh');
$("#home").after('<div data-role="page" data-add-back-btn="true" id=Gallery'+ i +
' class="gallery-page"> ' +
' <div data-role="header"></div> ' + ' <div data-role="content"> ' +
' <ul class="gallery"></ul> ' + ' </div> ' +
' </div> ');
}
});
})(i);
} //end of for loop
}
});
};
As you can see in the beginning i use the API to get information about the albums of the specific page : FB.api('169070991963/albums', function(response) {...}
Everything works as expected and i can get information as albumNames , albumCovers , albumIds etc .
Now for every album that i import , i want to have an array where i will save all of its pictures and thumbnails. For this reason i make another API call , FB.api(albumId + "/photos", function(response) {} .
I process the response like this :
for(var k=0; k<numberOfPhotos; k++){
albumThumbnails[i][k] = response.data[k].picture;
albumPhotos[i][k] = response.data[k].source;
}
At this point though i get the error : Uncaught TypeError: Cannot set property '0' of undefined
I cant understand what is undefined though... Any idea on this ?
*By the way the next API call that i make FB.api( albumCover, function(response) {..} to get the cover photos of the albums and create a jquery mobile listView , works too.
EDIT
The answer provided below solved the 2-dimensional table problem.
However now the error is : Uncaught TypeError: Cannot read property 'picture' of undefined
EDIT2
I am experiencing the same issue later in the code so i am making this EDIT. The code now looks as suggested like this :
<script>
var albumPhotos = new Array();
var albumThumbnails = new Array();
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '564984346887426', // App ID from the app dashboard
channelUrl : 'channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
FB.api('169070991963/albums', function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
// render photos
for(var i=0; i<response.data.length; i++){
(function (i) {
var albumName = response.data[i].name;
var albumCover = response.data[i].cover_photo;
var albumId = response.data[i].id;
var numberOfPhotos = response.data[i].count;
FB.api(albumId + "/photos", function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
for(var k=0; k<response.data.length; k++){
albumThumbnails[i] = albumThumbnails[i]||{};
albumThumbnails[i][k] = response.data[k].picture;
albumPhotos[i] = albumPhotos[i] || {};
albumPhotos[i][k] = response.data[k].source;
}
}
});
console.log(albumName);
FB.api( albumCover, function(response) {
if(!response || response.error) {
// render error
alert("Noo!!");
} else {
// render photos
$(".albums").append('<li>'+
'<a href="#Gallery' + i + '"' + 'data-transition="slidedown">'+
'<img src= "' + response.picture + '" />'+
'<h2>' + albumName + '</h2>'+
'<p>' + "Number of Photos: " + numberOfPhotos +'</p>'+
'</a>'+
'</li>')
.listview('refresh');
$("#home").after('<div data-role="page" data-add-back-btn="true" id=Gallery'+ i +
' class="gallery-page"> ' +
' <div data-role="header"><h1>Gallery</h1></div> ' + ' <div data-role="content"> ' +
' <ul class="gallery"></ul> ' + ' </div> ' +
' </div> ');
for(var x=0; x < albumPhotos[i].length; x++)
$('#Gallery' + i + ' .gallery').append('<li><img src="' + albumThumbnails[i][x] + '" /></li>');
}
});
})(i);
} //end of for loop
console.log(albumPhotos);
console.log(albumThumbnails);
}
});
};
I added this piece of code as you see :
for(var x=0; x < albumPhotos[i].length; x++)
$('#Gallery' + i + ' .gallery').append('<li><img src="' + albumThumbnails[i][x] + '" /></li>');
Every row in the 2dimensional table albumPhotos is an album and every column is a photo inside this album. With the for loop above i tried to create a list of Galleries that every Gallery has an album with all its photos.
Again i get the error :
Uncaught TypeError: Cannot read property '0' of undefined
Uncaught TypeError: Cannot read property '1' of undefined
Uncaught TypeError: Cannot read property '2' of undefined
Uncaught TypeError: Cannot read property '3' of undefined
.
.
.
Why do i get this now?
You have albumThumbnails and albumPhotos as empty arrays, and in the loop you are trying to add values into the array.
let us take the case where i = 0 your array albumThumbnails has a length of 0 that means albumThumbnails[0] is undefined, then you are trying to set albumThumbnails[0][0] which is giving the error.
The solution here is to first create an empty object at the index i if required then set its property
Looks like you are trying to create the object here
for(var k=0; k<numberOfPhotos && k < response.data.length; k++){
albumThumbnails[i] = albumThumbnails[i]||{};
albumThumbnails[i][k] = response.data[k].picture;
albumPhotos[i] = albumPhotos[i] || {};
albumPhotos[i][k] = response.data[k].source;
}

Extension stopped working with Google Chrome manifest v2

I am developing an extension for Google Chrome that was working perfectly, but now stopped working with version 2 of the manifest.
It is giving me the following error:
Uncaught SyntaxError: Unexpected end of input
popup.js:
chrome.tabs.getSelected(null, function (aba) {
link = aba.url;
titulo = aba.title;
document.getElementById('mensagem').value = link;
});
function GrabIFrameURL(feedDescription) {
var regex = new RegExp("iframe(?:.*?)src='(.*?)'", 'g');
var matches = regex.exec(feedDescription);
var url = '';
if (matches.length == 2) {
url = matches[1];
}
var quebra = url.split("/");
return quebra[4];
}
$(document).ready(function () {
if (localStorage.nome == '' || localStorage.nome == null || localStorage.email == '' || localStorage.email == null) {
jQuery('#formulario').hide();
jQuery('#erros').html('Configure seus dados aqui');
}
jQuery("#resposta").ajaxStart(function () {
jQuery(this).html("<img src='img/loading.gif'> <b>Sugestão sendo enviada, aguarde...</b>");
});
jQuery('#submit').click(function () {
var nome = localStorage.nome;
var email = localStorage.email;
var mensagem = titulo + "\n\n<br><br>" + link;
jQuery('#formulario').hide();
jQuery.post('http://blabloo.com.br/naosalvo/mail.php', {
nome: nome,
email: email,
mensagem: mensagem
},
function (data, ajaxStart) {
jQuery('#resposta').html(data);
console.log(data);
});
return false;
});
//Listagem de posts
var bkg = chrome.extension.getBackgroundPage();
jQuery('#close').click(function () {
window.close();
});
jQuery('#markeall').click(function () {
bkg.lidoAll();
$('.naolido').attr('class', 'lido');
});
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
$('.naolido').click(function (e) {
e.preventDefault();
klicked = $(this).attr('id');
console.log(klicked);
bkg.setLido(klicked);
$(this).attr('class', 'lido');
openLink($(this).attr('href'));
});
$('.lido').click(function (e) {
openLink($(this).attr('href'));
});
var openLink = function (link) {
chrome.tabs.create({
'url': link,
'selected': true
});
window.close();
}
});
I think the problem is in this part of popup.js:
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
You problem is actually in background.js on lines 12 and 20, you set localStorage.items to '' initially but then try to run a JSON.parse() on it later, but it's not JSON data so JSON.parse returns Unexpected end of input. And, JSON.parse isn't a function you define but a native browser function so, it shows the error as being on "line 1".
Try defining it as an empty array initially and then "pushing" to it as you are now.

Categories