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
}