loop div based on data obtained from php response - javascript

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');

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.

Cart only changes color of the first item of each game

I have this function that add's to my cart html, and its working fine. But when i add two of the same Item i get an error(only changes color in the first of each same item).
The console.log(changeBackgroundColor); console.log(changeColorText); gets only the first div of each game.
const addToCart = function () {
getJSON('games.json', function (err, data) {
var cartBets = document.getElementById('cart-bets');
if (err === null) {
console.log('Ocorreu um erro' + err);
} else {
let html = '';
regexPrice = data.types[whichLoteriaIsVar].price;
totalPrice += regexPrice;
let newTotalPrice = data.types[whichLoteriaIsVar].price
.toFixed(2)
.replace('.', ',');
html += '<div class="bar-side-cart">';
html += '<div class="side-by-side">';
html +=
'<div class="menu-thrash-save"><i onclick="deleteItemCart(this)" value="' +
data.types[whichLoteriaIsVar].price +
'" class="far fa-trash-alt" src="img/thrash-can.jfif" width=15 alt="Thrash"></i>
</div>';
html +=
'<div data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'" class="bets-backgroundcolor-lotos-container"></div>';
html += '<div class="top-by-top">';
html += '<p class="cart-right-text">' + totalNumbers + '</p>';
html += '<div class="side-by-side">';
html +=
'<div data-style="cart-text-thrash-' +
data.types[whichLoteriaIsVar].type +
'" class="bets-color-lotos-container">' +
data.types[whichLoteriaIsVar].type +
'</div>';
html += '<div class="cart-money">R$ ' + newTotalPrice + '</div>';
html += '</div>';
cartBets.innerHTML += html;
var changeBackgroundColor = document.querySelector(
'[data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'"]'
);
changeBackgroundColor.style.backgroundColor =
data.types[whichLoteriaIsVar].color;
var changeColorText = document.querySelector(
'[data-style="cart-text-thrash-' +
data.types[whichLoteriaIsVar].type +
'"]'
);
changeColorText.style.color = data.types[whichLoteriaIsVar].color;
console.log(changeBackgroundColor);
console.log(changeColorText);
getCartTotal();
}
});
};
document.querySelector() only returns the first matched element. Try using document.querySelectorAll() with a loop:
var changeBackgroundColor = document.querySelectorAll(
'[data-style="cart-thrash-side-bar-' +
data.types[whichLoteriaIsVar].type +
'"]'
);
changeBackgroundColor.forEach(
element => element.style.backgroundColor =
data.types[whichLoteriaIsVar].color
);

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
});
})

Outputing deeply nested JSON to HTML with 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);
});
});

Categories