Outputing deeply nested JSON to HTML with Javascript - javascript

So I can access the data I need by going to console.log(data.response[0].entities.urls);but how do I output the second array of entities into a HTML format. Is there a way of breaking up the JSON data using a for loop or something?
$(document).ready(function () {
$.getJSON('http://www.jamesam.ac/dev202/sdillon3/', function (data) {
var output = '<ul data-role="listview" data-filter="true">';
$.each(data.response, function (key, val) {
output += '<li>';
output += '<img src="' + val.user.profile_image_url + '" alt="' + val.text + '" />';
output += '<h3>' + val.user.name + '</h3>';
output += '<h4><i>' + val.user.screen_name + '</i></h4>';
output += '<p>' + val.text + '</p>';
output += '</li>';
}); // go through each post
output += '</ul>';
$('#feed').html(output);
console.log(data)
//console.log(data.response[0].entities.urls);//
});
});

Solved!
Just needed to write a good old for loop.
$(document).ready(function () {
$.getJSON('http://www.jamesam.ac/dev202/sdillon3/', function (data) {
var output = '<ul data-role="listview" data-filter="true">';
$.each(data.response, function (key, val) {
output += '<li>';
output += '<img src="' + val.user.profile_image_url + '" alt="' + val.text + '" />';
output += '<h3>' + val.user.name + '</h3>';
output += '<h4><i>' + val.user.screen_name + '</i></h4>';
output += '<p>' + val.text + '</p>';
for(var i = 0; i < val.entities.urls.length; i++)
{
output+= '<a href="' + val.entities.urls[i].url +'" </a>';
}
output += '</li>';
}); // go through each post
output += '</ul>';
$('#feed').html(output);
});
});

Related

why gihub pages wont load conditionals of JS script

My code is working properly on liveserver, but when I merge on github and open using github pages both conditionals "if" dont work at all. It's something that should be apllied on all pages.
This is how I load on HTML
<head>
<script src="./JS/header.js" defer></script>
</head>
<body>
<header id="header"></header>
This is the JS code:
function insertHeader(){
var codeBlock1 = '<div class="container">' +
'<img class="logo" src="./assets/logo.jpeg" alt="logo página">' +
'<div class="menu-section">' +
'<div class="container-menu">' +
'<input type="checkbox" id="checkbox-menu" />' +
'<label class="menu-button-container" for="checkbox-menu">' +
'<span></span>' +
'<span></span>' +
'<span></span>' +
'</label>' +
'<nav>' +
'<ul class="menu">' +
'</ul>' +
'</nav>' +
'</div>' +
'</div>' +
'</div>';
document.querySelector("#header").innerHTML += codeBlock1;
const urlAtual = window.location.pathname.substring(1);
if (urlAtual !== 'index.html'){
var codeBlockHome = '<li>' +
'Home' +
'</li>';
document.querySelector(".menu").innerHTML += codeBlockHome;
};
var codeBlockLocais =
'<li>' +
'Locais' +
'<ul class="submenu-locais">' +
'<li>Pontos Turísticos</li>' +
'</ul>' +
'</li>';
document.querySelector(".menu").innerHTML += codeBlockLocais;
if (urlAtual !== 'team.html'){
var codeBlockTeam = '<li>' +
'Equipe' +
'</li>';
document.querySelector(".menu").innerHTML += codeBlockTeam;
};
var codeBlockContato = '<li>' +
'Contato' +
'</li>';
document.querySelector(".menu").innerHTML += codeBlockContato;
for (i=0; i< estados.length; i++){
estadosNome[i] = estados[i].slice(0, -5);
estadosSigla[i] = estados[i].split(' ').pop();
var codeBlock2 = `<li>${estadosNome[i]}</li>`;
document.querySelector(".submenu-locais").innerHTML += codeBlock2;
}};
insertHeader();
Only "ifs" dont work, and I already solved this problem with CSS. But I'm still curious to why it worked on liveserver and not on github pages.

loop div based on data obtained from php response

The data
[{"id":"1","title":"science","added":"today","updated":"today","api":"25213","access":"0"}
[{"id":"2","title":"commerce","added":"","updated":"","api":"","access":"0"}]
The code
var data =
[{"id":"1","title":"science","added":"today","updated":"today","api":"25213","access":"0"}][{"id":"2","title":"commerce","added":"","updated":"","api":"","access":"0"}];
var htmlText = '';
for ( var key in data ) {
htmlText += '<div class="div-conatiner">';
htmlText += '<p class="p-name"> Name: ' + data[key].title + '</p>';
htmlText += '<p class="p-loc"> Location: ' + data[key].location + '</p>';
htmlText += '<p class="p-desc"> Description: ' + data[key].description + '</p>';
htmlText += '<p class="p-created"> Created by: ' + data[key].created_by + '</p>';
htmlText += '<p class="p-uname"> Username: ' + data[key].users_name + '</p>';
htmlText += '</div>';
}
$('body').append(htmlText);
this is the php response. i want to represent this data in html using js somehow how to do this
You have several mistakes in your code. As #RiggsFolly already mentioned your json is invalid. Furthermore you need to parse the data string as json object. Have a look at this code.
var data = '[{"id":"1","title":"science","added":"today","updated":"today","api":"25213","access":"0"},{"id":"2","title":"commerce","added":"","updated":"","api":"","access":"0"}]';
var htmlText = '';
var data = JSON.parse(data);
for ( var key in data ) {
htmlText += '<div class="div-conatiner">';
htmlText += '<p class="p-name"> Name: ' + data[key].title + '</p>';
htmlText += '<p class="p-loc"> Location: ' + data[key].location + '</p>';
htmlText += '<p class="p-desc"> Description: ' + data[key].description + '</p>';
htmlText += '<p class="p-created"> Created by: ' + data[key].created_by + '</p>';
htmlText += '<p class="p-uname"> Username: ' + data[key].users_name + '</p>';
htmlText += '</div>';
}
$('body').append(htmlText);
Since you are already using jQuery you could also create the div container in jQuery style.
var container = $('<div></div>').addClass('div-container');

My JSON data is loading in twice using AJAX, it is only supposed to load once on click

I am using AJAX and Jquery to load a json object into my web page. It works great however 50-70% of the time it loads in the json data to my page twice, it appends the second set of data to my page, is there a good way to ensure that my data only loads once?
my initial thought was to make the json call synchronous instead of asynchronous but that doesn't sound right, is there a better way of doing it?
$('#myResource').click(function() {
$.getJSON("data/preachers.json", function(result) {
$.each(result, function(i, field) {
$("#preachers").append( function() {
var preacher = '<div class="box box1">';
preacher += '<div class="image">';
preacher += '<a href=' + '"' + (field.link) + '"' + ' target="_blank">';
preacher += '<img src= "img/resources/' + (field.image) + '" alt="' + (field.name) + '" class="resource_image">';
preacher += '</a>';
preacher += '</div>'; //class = image
preacher += '<div class="text">';
preacher += '<p><h2>' + (field.name) + '</h2>';
preacher += (field.details) + '</p>';
preacher += '</div>'; //class=text
preacher += '</div>'; //class=box
return preacher;
});
});
});
});
Try
$('#myResource').unbind('click').click(function(){
})...
try to disable a button after click
$('#myResource').click(function() {
$('#myResource').prop('disabled' , true); //<<<<<<<<<<<<<<<< here
$.getJSON("data/preachers.json", function(result) {
$.each(result, function(i, field) {
$("#preachers").append( function() {
var preacher = '<div class="box box1">';
preacher += '<div class="image">';
preacher += '<a href=' + '"' + (field.link) + '"' + ' target="_blank">';
preacher += '<img src= "img/resources/' + (field.image) + '" alt="' + (field.name) + '" class="resource_image">';
preacher += '</a>';
preacher += '</div>'; //class = image
preacher += '<div class="text">';
preacher += '<p><h2>' + (field.name) + '</h2>';
preacher += (field.details) + '</p>';
preacher += '</div>'; //class=text
preacher += '</div>'; //class=box
return preacher;
});
$('#myResource').prop('disabled' , false); //<<<<<<<<<<<<<<<<<<<<<<< here
});
});
});
with the help of some of the comments, the answer ended up being that i needed to unbind click at the beginning of the function, and leaving it unbound:
$('#myResource').click(function() {
$( "#myResource").unbind( "click" );
$.getJSON("data/preachers.json", function(result) {
$.each(result, function(i, field) {
console.log('load everything');
$("#preachers").append( function() {
var preacher = '<div class="box box1">';
preacher += '<div class="image">';
preacher += '<a href=' + '"' + (field.link) + '"' + ' target="_blank">';
preacher += '<img src= "img/resources/' + (field.image) + '" alt="' + (field.name) + '" class="resource_image">';
preacher += '</a>';
preacher += '</div>'; //class = image
preacher += '<div class="text">';
preacher += '<p><h2>' + (field.name) + '</h2>';
preacher += (field.details) + '</p>';
preacher += '</div>'; //class=text
preacher += '</div>'; //class=box
return preacher;
});
});
});
});

TypeError: a is undefined in JavaScript

I have created a JSON read function but I get error:
TypeError: a is undefined
Here is my code:
$(function() {
var json = $.getJSON("http://localhost/stratagic-json/project_json.php", function() {
console.log("success");
});
var mhtml = '';
$.each(json.slider, function(key, val) {
mhtml += '<li><div class="proj-details-wrap"> <img src="images/' + val.image + '" />';
mhtml += '<div class="proj-badge">' + val.status + '</div>';
mhtml += '<div class="proj-name">' + val.name + ' <span>' + val.location + '</span> </div>';
mhtml += '</div>';
mhtml += ' <div class="container proj-desc">' + val.description + '</div>';
mhtml += '</li>';
});
var $ul = $('<ul class="slides">').append($(mhtml)); // append DOM only one time.
$('.slider').append($ul);
})
The problem is that $.getJSON is an asynchronous method and you're treating it synchronously. json.slider is undefined because $.getJSON actually returns a promise, not the data. The data needs to be accessed via the callback or a promise. This should work:
$(function() {
$.getJSON("http://localhost/stratagic-json/project_json.php", function(json) {
var mhtml = '';
$.each(json.slider, function(key, val) {
mhtml += '<li><div class="proj-details-wrap"> <img src="images/' + val.image + '" />';
mhtml += '<div class="proj-badge">' + val.status + '</div>';
mhtml += '<div class="proj-name">' + val.name + ' <span>' + val.location + '</span> </div>';
mhtml += '</div>';
mhtml += ' <div class="container proj-desc">' + val.description + '</div>';
mhtml += '</li>';
});
var $ul = $('<ul class="slides">').append($(mhtml)); // append DOM only one time.
$('.slider').append($ul);
});
})
You could also do something like this:
$(function() {
var jqXhr = $.getJSON("http://localhost/stratagic-json/project_json.php");
jqXhr.done( function (data) {
// Do something
});
})

Merge rows from $.each response

I am using the following code to present products that comes from an ajax response. My issue is that the table has many products with the same image. So I would like to find all the products with the same rec.Photo . Then I will present on one row the image and say that “we have variant of similar products click on the photo to see more… “
My issue is :
a)how I can find all the products with the same photo
b)how can I present on one row “see more similar products…” without destroy the loop
$.each(response, function (i, rec) {
if (i > 0) {
strproductlist += '<div class="gridItem listView">';
strproductlist += ' <div class="gridItemContent">';
strproductlist += '<div class="productPhoto">';
strproductlist += '<a title="' + rec.ProductName + '" href="ProductDetails.aspx?productid=' +
rec.ProductID + '">';
strproductlist += '<img alt="' + rec.ProductName + '" src="' + rec.Photo + '">';
strproductlist += '</a>';
strproductlist += '</div>';
strproductlist += '<div class="listViewProductDet">';
strproductlist += '<h2>';
strproductlist += '<a title="" href="ProductDetails.aspx?productid=' + rec.ProductID + '">' +
rec.ProductName + '</a>';
strproductlist += '</h2>';
strproductlist += '<p class="productCode">' + rec.ProductCode + '</p>';
strproductlist += '<ul class="fieldlist">';
strproductlist += '</div>';
strproductlist += '</div>';
strproductlist += '</div>';
}
//Edit
I am writing four sample records that presents 3 records with the same image
-------- ProductID=1 ProductName=product1 Photo=~/products/product1.jpg ProductCode=001
-------- ProductID=2 ProductName=product2 Photo=~/products/product1.jpg ProductCode=002
-------- ProductID=3 ProductName=product3 Photo=~/products/product1.jpg ProductCode=003
-------- ProductID=4 ProductName=product4 Photo=~/products/product2.jpg ProductCode=004
I hope below is what you are looking for. What I am doing is I am appending elements to body on each step so that I can identify whether the particular image with same url is present in body and if yes then don't render it and render what you need to like view more similar products. For time being I have just displayed an alert saying Image is present. You can write logic of displaying view similar products in that part!!
FIDDLE DEMO HERE
var data=[
{"ProductID":"1","ProductName":"product1", "Photo":"https://www.runtastic.com/shop/media/catalog/product/cache/2/image/9df78eab33525d08d6e5fb8d27136e95/o/r/orbit_with_clip_en_1.png","ProductCode":"001"},
{"ProductID":"2","ProductName":"product2", "Photo":"https://truegamers.com.my/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/3/_/3_83_6.jpg","ProductCode":"002"},
{"ProductID":"3","ProductName":"product3", "Photo":"https://www.runtastic.com/shop/media/catalog/product/cache/2/image/9df78eab33525d08d6e5fb8d27136e95/o/r/orbit_with_clip_en_1.png","ProductCode":"003"},
{"ProductID":"4","ProductName":"product4", "Photo":"https://truegamers.com.my/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/3/_/3_83_6.jpg","ProductCode":"004"}
];
$.each(data, function (i, rec) {
var strproductlist="";
var imgname=rec.Photo;
if($('.gridItem img[src="'+imgname+'"]').length)
{
alert('image present');
}
else
{
strproductlist += '<div class="gridItem listView">';
strproductlist += '<div class="gridItemContent">';
strproductlist += '<div class="productPhoto">';
strproductlist += '<a title="' + rec.ProductName + '" href="ProductDetails.aspx?productid=' +
rec.ProductID + '">';
strproductlist += '<img alt="' + rec.ProductName + '" src="' + rec.Photo + '">';
strproductlist += '</a>';
strproductlist += '</div>';
strproductlist += '<div class="listViewProductDet">';
strproductlist += '<h2>';
strproductlist += '<a title="" href="ProductDetails.aspx?productid=' + rec.ProductID + '">' +
rec.ProductName + '</a>';
strproductlist += '</h2>';
strproductlist += '<p class="productCode">' + rec.ProductCode + '</p>';
strproductlist += '<ul class="fieldlist">';
strproductlist += '</div>';
strproductlist += '</div>';
strproductlist += '</div>';
$('body').append(strproductlist)
}
});
img{
width:100px;
height:100px;
}
.gridItem{
float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
UPDATE
DEMO
Inside your if instead of alert I've written console.log which shows the parent that contains that image
if($('.gridItem img[src="'+imgname+'"]').length)
{
console.log($('.gridItem img[src="'+imgname+'"]').closest('.gridItem'));
}

Categories