I have this problem where my words of JSON won't load into my Webpage, the images do work already, fortunally..
I already have the images that needed to be loaded trough JSON into my Webpage.
I still need some words to load trough JSON into my Webpage,
{"main_object": {
"imagesJ": ["beak", "cat", "egg", "meel", "milk", "passport", "spoon", "thee"],
"wordsJ": ["næb", "kat", "æg", "mel", "mælk", "pas", "ske", "te"]
}
}
var jsonData = "noJson";
var hr = new XMLHttpRequest();
$(document).ready(function(){
var jsonData = 'empty';
$.ajax({
async: false,
url: "./js/data.json",
dataType: 'html',
success: function(response){
jsonData = JSON.parse(response);
console.log('ok');
imagesJ = jsonData.main_object.imagesJ;
wordsJ = jsonData.main_object.wordsJ;
for(i = 0; i < imagesJ.length; i++) {
images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
}
document.getElementById('images') = html;
for (i = 0; i < wordsJ.length; i++) {
wordsJ.innerHTML += '<span>' + wordsJ[i] + '</span>';
}
document.getElementById('words') = html;
},
error: function(){
console.log('JSON could not be loaded.');
}
});
console.log(jsonData);
});
header {
height: 5%;
}
body {
background-color: #f0f0f0;
}
.container {
height: 90%;
}
.images img {
height: 100px;
width: 100px;
}
footer{
height: 5%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sleepopdracht</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/css.css">
</head>
<body>
<header>
</header>
<div class="container" id="container"><div class="images" id="images"></div>
<div class="words" id="words"></div>
</div>
<footer>
</footer>
<script type="text/javascript" src="js/javascript.js"></script>
</body>
</html>
In the Javascript you can see that I loaded the words a little like the images, as far as I know it should just work, but the console reports an
Uncaught ReferenceError: Invalid left-hand side in assignment ~ jquery.min.js:4
I can't seem to figure out te source of the problem, neighter do I know how to solve it full.
It seems that The error exists even if i commend the Words loop out, The Error existed already without the code calling the words JSON. But now the problem still is that I can't find the source of the problem, if I found it, it is probably easy to solve. Since the last time I checked, the code ran perfectly without the Words Loop
I see that you havn't defined imagesJ and wordsJ
var imagesJ;
var wordsj;
And you need to do something like this
var word = document.getElementById('words');
var html = '';
for (i = 0; i < wordsJ.length; i++) {
html += '<span>' + wordsJ[i] + '</span>';
}
word.innerHTML = html;
Final File
var jsonData = "noJson";
var hr = new XMLHttpRequest();
var imagesJ;
var wordsj;
$(document).ready(function(){
var jsonData = 'empty';
$.ajax({
async: false,
url: "./js/data.json",
dataType: 'html',
success: function(response){
jsonData = JSON.parse(response);
console.log('ok');
imagesJ = jsonData.main_object.imagesJ;
wordsJ = jsonData.main_object.wordsJ;
for(i = 0; i < imagesJ.length; i++) {
images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
}
document.getElementById('images') = html;
var word = document.getElementById('words');
var html = '';
for (i = 0; i < wordsJ.length; i++) {
html += '<span>' + wordsJ[i] + '</span>';
}
word.innerHTML = html;
},
error: function(){
console.log('JSON could not be loaded.');
}
});
console.log(jsonData);
});
Try changing this code:
for (i = 0; i < wordsJ.length; i++) {
wordsJ.innerHTML += '<span>' + wordsJ[i] + '</span>';
}
document.getElementById('words') = html;
to:
var words = document.getElementById('words')
for (i = 0; i < wordsJ.length; i++) {
words.innerHTML += '<span>' + wordsJ[i] + '</span>';
}
I found that the problem was in
document.getElementById('images') = html;
this was wrong, first I didn't call html at all so I made a var after console log of html with an empty string.
console.log('ok');
var imagesJ = jsonData.main_object.imagesJ;
var wordsJ = jsonData.main_object.wordsJ;
var html = '';
var html2 = '';
The var html2 is for the words.
then my document.getElementById was not complete (that was the Error)
This was the proper code for the document.
document.getElementById('images').innerHTML = html;
Then I had,
images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
wich needed to be this,
html += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
So my full code then was,
var jsonData = "noJson";
var hr = new XMLHttpRequest();
$(document).ready(function(){
var jsonData = 'empty';
$.ajax({
async: false,
url: "./js/data.json",
dataType: 'html',
success: function(response){
jsonData = JSON.parse(response);
console.log('ok');
var imagesJ = jsonData.main_object.imagesJ;
var wordsJ = jsonData.main_object.wordsJ;
var html = '';
var html2 = '';
for(i = 0; i < imagesJ.length; i++) {
html += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
//images.innerHTML += '<img src="/sleepopdracht/img/'+imagesJ[i]+'.jpg" alt="images" id="'+[i]+'">';
}
document.getElementById('images').innerHTML = html;
//$('#images').append(html);
for (i = 0; i < wordsJ.length; i++) {
words.innerHTML += '<span>'+wordsJ[i]+'</span>';
}
document.getElementById('words').innerHTML = html2;
},
error: function(){
console.log('JSON could not be loaded.');
}
});
console.log(jsonData);
});
Altough I still don't have the words in my browser, the Error is resolved.
Thanks Everyone :D Happy programming!
Related
Hi there I'm trying to populate div with data from ajax request, the idea is to use Ajax to get temperature from multiple sensors and for every sensor temperature data I want a separate div column with the data, So on document.ready I use ajax get once to popualte the main page div with the div columns to get the results, but after that I want to use ajax again every 10 seconds to update the data, but how can I do it not generating the containers for the data again? Because of waht I have right now I can't make it to work when I try to make a filter to show/hide the div for specific location.
$(document).ready(function(){
var menu_list = [];
var tr_str = [];
var temp_int= [];
$.ajax({
url: 'getData.php',
type: 'get',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var location = response[i].location;
temp_int[i] = response[i].temp_int;
var temp = response[i].temp;
var hum = response[i].hum;
var dew = response[i].dew;
tr_str[i] = "<div id='locc" + i + "' class='location'>" +
"<span class='title'>" + location + "</span>" +
"<div class='temp" + i + "'><span>Temperatura: </span><span id='check'>" + temp + " °C</span></div>" +
"<div><span>Względna wilgotność: </span><span>" + hum + " %RH</span></div>" +
"<div><span>Punkt rosy: </span><span>" + dew + " °C</span></div>" +
"</div>";
menu_list[i] = "<label for='loc" + i + "'>" +
"<input type='checkbox' id='loc" + i + "' checked='checked'/>" +
"<span class='css-checkbox'></span>" +
"<p>" + location + "</p>" +
"</label>";
}
$("#nav").append(menu_list);
$("#data").html(tr_str);
for(var i=0; i<len; i++){
if (temp_int[i] >= 250) {
$(".temp" + i).css("background-color", "#ff0000");
}
else if (temp_int[i] >= 235) {
$('.temp' + i).css("background-color","#f1c40f");
}
else {
$('.temp' +i).css("background-color","#3498db");
}
}
}
});
$("#loc1").change(function () {
if (this.checked){
$("#locc1").show(!this.checked);
}else {
$("#locc1").hide(!this.checked);
}
});
});
setTimeout(fetchdata,5000);
function fetchdata(){
var tr_str = [];
var temp_int= [];
$.ajax({
url: 'getData.php',
type: 'get',
dataType: 'JSON',
cache: false,
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var location = response[i].location;
temp_int[i] = response[i].temp_int;
var temp = response[i].temp;
var hum = response[i].hum;
var dew = response[i].dew;
tr_str[i] = "<div id='locc" + i + "' class='location'>" +
"<span class='title'>" + location + "</span>" +
"<div class='temp" + i + "'><span>Temperatura: </span><span id='check'>" + temp + " °C</span></div>" +
"<div><span>Względna wilgotność: </span><span>" + hum + " %RH</span></div>" +
"<div><span>Punkt rosy: </span><span>" + dew + " °C</span></div>" +
"</div>";
}
$("#data").html(tr_str);
for(var i=0; i<len; i++){
if (temp_int[i] >= 250) {
$(".temp" + i).css("background-color", "#ff0000");
}
else if (temp_int[i] >= 235) {
$('.temp' + i).css("background-color","#f1c40f");
}
else {
$('.temp' +i).css("background-color","#3498db");
}
}
},
complete:function(){
setTimeout(fetchdata,5000);
}
});
}
function openNav() {
document.getElementById("nav").style.width = "350px";
document.getElementById("data").style.marginLeft = "350px";
}
function closeNav() {
document.getElementById("nav").style.width = "0";
document.getElementById("data").style.marginLeft = "0";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="lib/style.css">
</head>
<body>
<div id="nav" class="menu">
×
<button>Uncheck all</button>
</div>
<div class="nav-wrapper">
<span onclick="openNav()">☰</span>
</div>
<div id="data" class="wrapper"></div>
</body>
</html>
You can see that I use almost the same Ajax request again, is there a way to get teh data at first and generate the divs for the data and then just get the data every 10 seconds and update it only withou generating again the divs?
I'm thinking that what I have right now is making tis unable to work
var $checkboxes = $("#nav :checkbox");
var $button = $("#nav button");
function allChecked(){
return $checkboxes.length === $checkboxes.filter(":checked").length;
}
function updateButtonStatus(){
$button.text(allChecked()? "Uncheck all" : "Check all");
}
function handleButtonClick(){
$checkboxes.prop("checked", allChecked()? false : true)
}
$button.on("click", function() {
handleButtonClick();
updateButtonStatus();
checking();
});
$checkboxes.on("change", function(){
updateButtonStatus();
});
function openNav() {
document.getElementById("nav").style.width = "250px";
}
function closeNav() {
document.getElementById("nav").style.width = "0";
}
function checking() {
var temps = <?php echo json_encode($temps); ?>; //I know this is wrong I would change the loop iteration but it is not working even for one static element when I change it.
$.each( temps, function( index, value ){
$('#loc'+index).change(function () {
if( this.checked ) {
$('#locc'+index).show(!this.checked);
} else {
$('#locc'+index).hide(!this.checked);
}
}).change();
});}
Here is the php file code I'm geting using ajax:
<?php
require 'lib/locations.php';
$search = array('STRING: ', '"');
$search2 = array('INTEGER: ', '"');
$replace = array('','');
$return_arr = array();
for ($i = 0; $i < $c; $i++) {
$temp_int = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.3.1.0");
$temp_int = str_replace($search2,$replace,$temp_int);
$temp = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.1.0");
$temp = str_replace($search,$replace,$temp);
$hum = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.2.0");
$hum = str_replace($search,$replace,$hum);
$dew = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.3.0");
$dew = str_replace($search,$replace,$dew);
$loc = $location[$i];
$return_arr[] = array("location" => $loc,
"temp_int" => $temp_int,
"temp" => $temp,
"hum" => $hum,
"dew" => $dew);
}
echo json_encode($return_arr);
?>
The generated data is an array of one integer and strings
something like this:
var response =[{
"location": "location_1"
"temp_int":250,
"temp":"30.5",
"hum":"49.8",
"dew":"8.5"
},
{"location": "location_1"
"temp_int":250,
"temp":"30.5",
"hum":"49.8",
"dew":"8.5"
}, etc.]
I got an array from json and I need to put each item in a <li> on my html
something like this :
names : {john, paul, ringo,george}
into <li>john</li>..
my code:
<div id="demo"></div>
script:
function onLocationsReceived(data) {
console.log("recievd");
for (var i = 0; i < data[0].Sensors.length; i++) {
var sensorNames = data[0].Sensors[i].Name;
document.getElementById("demo").innerHTML = sensorNames;
console.log(sensorNames);
}
}
on the concole.log it prints just fine..
document.getElementById("demo").innerHTML = '<li>' + sensorNames '</li>
something like that???
Using something like below
function onLocationsReceived(data){
var html="";
for (var i = 0; i < data[0].Sensors.length; i++) {
var sensorNames = data[0].Sensors[i].Name;
html+="<li>"+sensorNames+"</li>";
console.log(sensorNames);
}
document.getElementById("demo").innerHTML=html;
}
You can use syntax below
document.getElementById('demo').innerHTML ='<li>' + sensorNames + '</li>'
You should cache the iterative sensorNames into a var with the li and then replace the innerHTML:
var content = "",
sensorNames;
for (var i = 0; i < data[0].Sensors.length; i++) {
sensorNames = data[0].Sensors[i].Name;
content += "<li>" + sensorNames + "</li>";
}
document.getElementById("demo").innerHTML = content;
I'm running into a problem when trying to add in the search functionality, showList().
It seems to bog down the client so much that Chrome wants to kill the page each time I type into the input field. I'm clearly a novice JS writer, so could I be running an infinite loop somewhere I don't see? Also, any advice to get the search functionality working properly would be hugely appreciated. I don't think I'm using the correct selectors below for the show/hide if statement, but I can't think what else to use.
$(document).ready(function(){
showList();
searchBar();
});
function showList() {
$("#show-records").click(function(){
$.getJSON("data.json", function(data){
var json = data;
$("show-list").append("<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
$("#show-list").append("<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>");
$("show-list").append("</table>");
}
//end getJSON inner function
});
//end click function
});
//end showList()
};
function searchBar() {
//AJAX getJSON
$.getJSON("data.json", function(data){
//gathering json Data, sticking it into var json
var json = data;
for(var i = 0; i < json.length; i++) {
//putting the json objects into var obj
var obj = json[i];
function contains(text_one, text_two) {
if (text_one.indexOf(text_two) != -1)
return true;
}
//whenever anything is entered into search bar...
$('#search').keyup(function(obj) {
//grab the search bar content values and...
var searchEntry = $(this).val().toLowerCase();
//grab each td and check to see if it contains the same contents as var searchEntry - if they dont match, hide; otherwise show
$("td").each(function() {
if (!contains($(this).text().toLowerCase(), searchEntry)) {
$(this).hide(400);
} else {
$(this).show(400);
};
})
})
}
});
};
body {
background-color: lightblue;
}
tr:first-child {
font-weight: bold;
}
td {
padding: 3px;
/*margin: 10px;*/
text-align: center;
}
td:nth-child(6) {
padding-left: 50px;
}
td:nth-child(7) {
padding-left: 10px;
padding-right: 10px;
}
#filter-count {
font-size: 12px;
}
<html>
<head>
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script language="javascript" src="process.js"></script>
<link rel="stylesheet" type="text/css" href="./mystyle.css">
</head>
<body>
<a href="#" id='show-records'>Show Records</a><br>
<label id="searchBar">Search: <input id="search" placeholder="Enter Specialist Name"></label>
<span id="search-count"></span>
<div id="show-list"></div>
</body>
</html>
Problem appears to be that you can't treat append as if it was a text editor and you are writing html.
Anything that gets inserted needs to be a proper element ... not a start tag, then some text...then a close tag.
We can however modify your code slightly to produce html strings and then add that at the end
$.getJSON("data.json", function(data){
var json = data;
var html="<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
html+= "<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>";
}
html+= '</table>';
$("#show-list").html(html);
//end getJSON inner function
});
I'm very new to both JQuery and Javascript. I have an feed, I would like to display these feed inside a collapsible div AS a collapsible div. I have the following Javascript file:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
google.setOnLoadCallback(showFeed);
function showFeed() {
var feed = new google.feeds.Feed("http://www.varzesh3.com/rss");
feed.setNumEntries(10);
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("headlines");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var di = document.createElement("div").setAttributeNode("data-role", "collapsible");
di.innerHTML = '<h3>' + entry.title + '</h3>';
di.innerHTML += '<p>' + entry.contentSnippet + '</p>';
container.appendChild(di);
}
} else {
var container = document.getElementById("headlines");
container.innerHTML = '<li>Get your geek news fix at site</li>';
}
});
}
</script>
<body>
<div data-role="collapsible-set" id="headlines"></div>
</body>
This should fetch all my feed names and put them in a collapsible div, it does exactly that but it shows the names as plain HTML text instead of a JQuery Mobile collapsible div.
#AML, that is more a comment than an answer because a don't analyse your entire code, but I will put here for formatting purposes.
In the line:
var di = document.createElement("div").setAttributeNode("data-role", "collapsible");
You don't take a pointer(di) to the new created element, you take a result of the setAttributeNode(...), You need to split the code in two lines like that:
var di = document.createElement("div");
di.setAttribute("data-role", "collapsible");
There are a problem with setAttributeNode actually is setAttribute.
Now is working, see at http://pannonicaquartet.com/test/feeds.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
.collapsible{
display : none;
}
h3{
background-color : lightgray;
}
</style>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load("feeds", "1");
function showFeed() {
var feed = new google.feeds.Feed("http://www.varzesh3.com/rss");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("headlines");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.onclick = function(evt){
var elP = this.children[1];
if(elP.style.display == 'inline'){
elP.style.display = 'none';
}else{
elP.style.display = 'inline';
}
};
div.innerHTML = '<h3>' + entry.title + '</h3>';
div.innerHTML += '<p class="collapsible">' + entry.contentSnippet + '</p>';
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(showFeed);
</script>
On clicking the td class="bgimg", I'm calling another function. How do I add a class to the td which I clicked?
/*This function creates a list of tabs*/
BCL.onSearchResponse = function(jsonData) {
BCL.jsonData = jsonData;
var str = "<table id=\"playlistTable\" cellspacing=\"1\"><tbody><tr>";
var html = "";
for (var i = 0; i < jsonData["items"].length; i++) {
var playlist = jsonData["items"][i];
html = "<td class=\"bgimg\" onclick=\"BCL.onPlaylistSelect(" + i +")\">{{name}}</td>";
str += BCL.markup(html,playlist);
}
str += "</tr></tbody></table>";
//console.log(str);
document.getElementById("results").innerHTML = str;
// load the first playlist
BCL.onPlaylistSelect(0);
}
function hasClass(element,clss) {
return element.className.match(new RegExp('(\\s|^)'+clss+'(\\s|$)'));
}
function addClass(element,clss) {
if (!this.hasClass(element,clss)) element.className += " "+clss;
}
BCL.onPlaylistSelect = function(something, element) {
element.addClass("myClass");
//do stuff
};
BCL.onSearchResponse = function(jsonData) {
BCL.jsonData = jsonData;
var str = "<table id=\"playlistTable\" cellspacing=\"1\"><tbody><tr>";
var html = "";
for (var i = 0; i < jsonData["items"].length; i++) {
var playlist = jsonData["items"][i];
html = "<td class=\"bgimg\" onclick=\"BCL.onPlaylistSelect(" + i +", this)\">{{name}}</td>";
str += BCL.markup(html,playlist);
}
str += "</tr></tbody></table>";
//console.log(str);
document.getElementById("results").innerHTML = str;
// load the first playlist
BCL.onPlaylistSelect(0);
};