How to fetch the json array? - javascript

I have my external json and trying to fetch the json values dynamically in my javascript. I am able to fetch the first level values and when I try to fetch the array object, it is showing my result as undefined. However when I try this "alert(data.siteAttribute[0].data[0].label);" its returning the the value.
Here is the following that I have tried
$(document).ready(function() {
$.getJSON("https://api.myjson.com/bins/naqzj", function(data) {
$(".test").html('<div class="card-deck">');
var output = "";
for (var i in data.siteAttribute) {
output += "<div class='col-md-4 col-lg-3'><div class='card site-attribute-card'>";
output += "<span class='sticker sticker-rounded sticker-top-right'><span class='inline-item'><img height='50' width='50' src='"+data.siteAttribute[i].data.imageURL +"'/></span></span>";
output += "<div class='card-body'> <div class='card-row'>"
output +="<div class='card-title text-truncate'>" + data.siteAttribute[i].data.label + "</div>";
output += "<div class='card-text'>" + data.siteAttribute[i].data.value + "</div>";
output +="<div class='card-title text-truncate'>" + data.siteAttribute[i].data.operatinghours + "</div>";
output += "<div class='card-text'>" + data.siteAttribute[i].data.hours + "</div>";
output +="<div class='card-title text-truncate'>" + data.siteAttribute[i].data.areaLabel + "</div>";
output += "<div class='card-text'>" + data.siteAttribute[i].data.areaValue + "</div>";
output +="<div class='card-title text-truncate'>" + data.siteAttribute[i].dateModified + "</div>";
output +="<div class='card-text'>" + data.siteAttribute[i].date + "</div>";
output += "</div></div>";
output += "<div class='card-footer'>";
output += "<div class='card-title text-truncate' title='Card Title'>"+ data.siteAttribute[i].name + "<span class='label label-tag label-category right'><span class='label-item label-item-expand'>"+data.siteAttribute[i].status+"</span></span></div>";
output += "<div class='card-links'><a href='/group/retail/site-management-form'>Edit</a><a class='right' href='#'>View</a></div></div>"
output += "</div></div>";
}
$(".test .card-deck").append(output);
$(".test .card-deck").append('</div>');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="test container">
</div>
Here is my sample fiddle for reference. I am missing the loop fro the array and have no clues on how to figure out. Thanks in advance!

data.siteAttribute[i].data is an array
So you can use data.siteAttribute[i].data[0] to get the first item or you'll have to loop through that data as well.

Looks like you are only having issues with having nested loops. To loop over an array of objects I suggest I suggest using Array.prototype.forEach. To simplify your demo I have removed all the HTML markup and nested two forEach loops to parse over the JSON data. Please review the demo and inline comments below:
$(document).ready(function() {
$.getJSON("https://api.myjson.com/bins/naqzj", function(result) {
// Loop over the top level attributes
result.siteAttribute.forEach(function(attr) {
// Loop over the attribute `data` array
attr.data.forEach(function(attrData) {
// For demo purposes, loop over the inner data object and print its props and values
for (var key in attrData) {
console.log(key, ' -> ', attrData[key]);
}
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

how to check for changed values in firebase real time database and make them show up in html table?

I have been able to remove entries from the table once it's been removed on the database and also able to add entries once they've been edited.
how to check if data is already in html table using firebase real time database?
I am now looking for how to look for live changes to the database.
var database = firebase.database().ref().child('transactions');
database.on('child_added', function(snapshot){
var data = snapshot.val();
var content = '<tr id="'+snapshot.key+'">';
content += '<td>' + data.CustomerName + '</td>';//column2
content += '<td>' + data.TimeEffected + '</td>'; //column1
content += '<td>' + data.DateEffected + '</td>'; //column1
content += '<td>' + data.Successful + '</td>'; //column1
content += '</tr>';
$('#ex-table').append(content);
database.on('child_removed', function(snapshot){
$('#'+snapshot.key).remove()
});
});
I tried using this:
database.on('child_changed', function(snapshot){
$('#'+snapshot.key).change()
});
I tried putting it under the remove method but that has been unsuccessful.
The $('#'+snapshot.key) gets the correct element in the HTML, but jQuery's change() method does not do what you think it does. Read the linked documentation to learn what it actually does.
If you think about if for a moment this should make sense: how would a built-in method from jQuery know how to update your HTML structure?
Only your code knows what HTML it created for the data in the snapshot. You will need to replicate (some of) your code that creates the HTML in the child_added callback into the child_changed callback.
Something like this:
database.on('child_changed', function(snapshot){
var data = snapshot.val();
var content = '<tr id="'+snapshot.key+'">';
content += '<td>' + data.CustomerName + '</td>';//column2
content += '<td>' + data.TimeEffected + '</td>'; //column1
content += '<td>' + data.DateEffected + '</td>'; //column1
content += '<td>' + data.Successful + '</td>'; //column1
content += '</tr>';
$('#'+snapshot.key).replaceWith(content)
});

Dynamically adding JSON data to Bootstrap slideshow via javascript

I have a JSON feed I'm accessing to pull data from and am using a little javascript and jQuery to place the data into a Bootstrap carousel. I am having trouble figuring out how to properly loop the data, to feed the carousel appropriately. What I would like to do, is loop through each JSON value, and sequentially feed three values per row of the carousel. My attempts resulted in three sequential values showing in all iterations of the carousel rows, instead of moving on to the next three values per row.
So, in essence, I seem to be having a loop issue. I am having trouble figuring out the proper way to loop this. I've tried several options, but none have worked appropriately. Again, all I want is to feed the carousel with 3 distinct items/values per row.
I noticed a fairly similar question was posted regarding feeding an unordered list, but my implementation of the response did not work.
Thanks for any help.
<script>
var $ = jQuery.noConflict();
var counter = 1;
// Set the global configs to synchronous
$.ajaxSetup({
cache: true,
async: false
});
$(document).ready(function() {
$.getJSON('http:JSON_feedlocation......', function(data) {
html = "";
// Carousel wrapper divs - exempt from loop
html += "<div class='container carousel carousel-show-one-at-a-time slide' data-interval='6000' data-ride='carousel' id='the-new-marketing-carousel'>";
html += "<div class='carousel-inner'>";
// First Loop - row wrapper
for (var i in data.content) {
html += "<div class='item'>";
html += "<div class='newsblock panel-display etowah-newsblock clearfix etowah-newsblock-trio'>";
html += "<div class='container'>";
html += "<div class='row'>";
// Second loop to pull in specific values, three values per loop
for (var i = 0; i < 3; i++) {
var type = data.content[i]["type"];
var title = data.content[i]["title"];
var url = data.content[i].url;
var created = data.content[i].created;
var teaser = data.content[i]["teaser"];
html += "<div id='carousel-blocks' class='newsblock-col-single newsblock__content--first col-md-4 col-sm-4 col-tiny-4'>";
html += "<div class='panel-pane pane-bundle-etowah-newsblock-item'>";
html += "<div class='news-block news-block--medium'>";
html += "<a href='"+ url +"''>";
html += "<img class='block__img' src='http://img" + data.content[i].thumbnail.split('public/')[1].split('?')[0] + "' />";
html += "</a>";
html += "<h3 class='news-block__title'>"
html += "<a href='"+ url +"'>"+ title +"";
html += "</a>";
html += "</h3>";
html += "</div>";
html += "</div>";
html += "</div>";
}
html += "</div>";
html += "</div>";
html += "</div>";
html += "</div>";
}
html += "</div>";
html += "</div>";
html += "<a class='left carousel-control' href='#the-new-marketing-carousel' data-slide='prev'><i class='glyphicon glyphicon-chevron-left'></i></a>";
html += "<a class='right carousel-control' href='#the-new-marketing-carousel' data-slide='next'><i class='glyphicon glyphicon-chevron-right'></i></a>";
counter = counter + 1;
document.getElementById("api-carousel").innerHTML=html;
$(".carousel div.item").first().addClass("active");
});
});
</script>
<div id="api-carousel">
<!-- Carousel api -->
</div>

JavaScript function onclick runs automatically

i have this code in while loop in JavaScript. As you can see i am adding every loop to with ID page, another divs. Every div has onclick handler which can execute MyFunction with variable. My problem is that, my script onlick runs automatically when my page is loaded. But i need to run MyFunction only if i click on the div.
Code:
document.getElementById("page").innerHTML += "<div style='width:100px; float:left;' onclick='" + MyFunction(variable) + "'>" + AnotherVariable + "</div>";
Thank you
You're a bit off ... try ...
document.getElementById("page").innerHTML += "<div style='width:100px; float:left;' onclick='MyFunction(" + variable + ")'>" + AnotherVariable + "</div>";
.. if you don't want the function to run.
In particular, look here:
"<div ... onclick='MyFunction(" + variable + ")'>"
UPDATE 1:
"Variable is string." Then, here's the modification:
document.getElementById("page").innerHTML += "<div style='width:100px; float:left;' onclick='MyFunction(\"" + variable + "\")'>" + AnotherVariable + "</div>";

Setting up a local proxy to access imdb

I want to run a search for everything under a give title name for example star wars like this search here http://www.imdb.com/xml/find?json=1&nr=1&tt=on&q=star%20wars
I want to list all the results in a table format
here is the code i have so far i have had to change from using the easy omdb api because that will only allow up to ten results
right now i keep getting javascript errors any help plz i am aware i need to set up a localproxy NEED HELP PLZ
Would Love Examples
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Sample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$("#SampleSearchButton").click(function() {
getImdbInfo($("#title").val());
})
});
// The function below takes the entered title and searchs imdb for a match then it displays as followed
function getImdbInfo(Title) {
$.ajax({
url: "http://www.imdb.com/xml/find?json=1&nr=1&tt=on&q=" + Title,
cache: false,
dataType: "json",
success: function(data) {
// you get an object for iteration, the keys are Title, Type, Year, imdbID
console.log(data);
var str = '<table>';
str += "<thead><th>Index</th><th>Title</th><th>Type</th><th>Year</th><th>imdbID</th></thead>"
// iterate over the data result set
$.each(data.Search, function(index, element) {
str += "<tr>";
str += "<td>" + index + "</td>";
str += "<td>" + element.Title + "</td>";
str += "<td>" + element.Type + "</td>";
str += "<td>" + element.Year + "</td>";
str += "<td>" + element.imdbID + "</td>";
str += "</tr>";
});
str += '</table>';
// insert the html
$("#SampleResults").html(str);
},
error: function (request, status, error) { alert(status + ", " + error); }
});
}
</script>
</head>
<body>
<!-- search textbox -->
<input type="text" id="title" placeholder="Enter Name for search">
<!-- do search button -->
<button type="text" id="SampleSearchButton">Search</button>
<!-- display results container -->
<div id="SampleResults"></div>
</body>
</html>
you enter the title
the title is append to a url, which calls your local php file
the local php file accepts the title and attaches it the API url you want to call
the request is made and the content is returned
returned content is then accepted by js
check console.log for exact data structure
to main keys "title_popular" and "title_exact", that's why there are two tables
watch out for "description" and "title_description", both seem to be the same (API BUG?), so they are printed twice!
i don't have the time to structure the table fully
maybe you should ask someone, how to print the multilevel object more elegant
PHP
imdb-fetcher.php
<?php
$title = $_GET['title']; // <- you need to secure this
echo file_get_contents(
'http://www.imdb.com/xml/find?json=1&nr=1&tt=on&q=' . $title
);
HTML
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Sample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$("#SampleSearchButton").click(function() {
getImdbInfo($("#title").val());
})
});
// The function below takes the entered title and searchs imdb for a match then it displays as followed
function getImdbInfo(title) {
$.ajax({
type: 'GET',
url: "imdb-fetcher.php?title=" + title, // <-- request to PHP data fetcher
dataType: "json",
success: function(data) {
// you get an object for iteration, see console for keys
console.log(data);
// table for title_popular
var str = '<table>';
str += "<thead><th>Index</th><th>id</th><th>title</th><th>title_desc</th><th>year</th><th>description</th></thead>";
$.each(data.title_popular, function(index, element) {
str += "<tr>";
str += "<td>" + index + "</td>";
$.each(element, function(key, element) {
str += "<td>" + element + "</td>";
});
str += "</tr>";
});
str += '</table>';
// table for title_exact
str += '<table>';
str += "<thead><th>Index</th><th>id</th><th>title</th><th>title_desc</th><th>year</th><th>description</th></thead>";
$.each(data.title_exact, function(index, element) {
str += "<tr>";
str += "<td>" + index + "</td>";
$.each(element, function(key, element) {
str += "<td>" + element + "</td>";
});
str += "</tr>";
});
// insert the html
$("#SampleResults").html(str);
},
error: function (request, status, error) { alert(status + " - " + error); }
});
}
</script>
</head>
<body>
<!-- search textbox -->
<input type="text" id="title" placeholder="Enter Name for search">
<!-- do search button -->
<button type="text" id="SampleSearchButton">Search</button>
<!-- display results container -->
<div id="SampleResults"></div>
</body>
</html>
Result

jQueryUI dialog not displaying

I am trying to generate a jQuery UI dialog using a function. The function is triggered by an onClick event and it is executing, but for some reason the dialog will not display. I'm sure it is something simple.
I would prefer to create the dialog in this way if possible as loading the dialog from a separate html page causes same origin issues on chrome. The code is part of a browser extension that can possibly be used offline so this way allows for that without the same origin restrictions.
I have already created a similar dialog of this nature that worked which had a parameter appended between tags. I have tried that with the current one and it has not worked.
I have the latest jQuery ui and jQuery libs added in the main page.
I'm new to javascript and jQuery but if anyone could provide some help I'd greatly appreciate it.
Thanks,
Joe
function imageSelection() {
var NewDialog = $('<div id="imageSelectionDialog"> ' +
"<ol id= \"selectable\">" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image1.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image2.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image3.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image4.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image5.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image6.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image7.jpg\"/></li>" +
"<li class=\"ui-state-default\"><img src=\"images/stock/image8.jpg\"/></li>" +
"</ol>" +
"<form id=\"pieceSelection\">" +
"<div id=\"imageInput\">" +
"<input type=\"text\" id=\"image\" value=\"images/stock/walkin.jpg\"" +
"title=\"Select an image above or Paste a URL e.g http://server.com/path/to/image.jpg\"/>" +
"</div>" +
"<div id=\"radio\">" +
"<input type=\"radio\" id=\"radio1\" name=\"radio\" checked/>" +
"<label for=\"radio2\">x3</label>" +
"<input type=\"radio\" id=\"radio2\" name=\"radio\"/>" +
"<label for=\"radio3\">x4</label>" +
"<input type=\"radio\" id=\"radio3\" name=\"radio\"/>" +
"<label for=\"radio4\">x5</label>" +
"<input type=\"radio\" id=\"radio4\" name=\"radio\"/>" +
"<label for=\"radio5\">x6</label>" + 7
"<input type=\"radio\" id=\"radio5\" name=\"radio\"/>" +
"<label for=\"radio6\">x7</label>" +
"<input type=\"radio\" id=\"radio6\" name=\"radio\"/>" +
"<label for=\"radio7\">x8</label>" +
"<input type=\"radio\" id=\"radio7\" name=\"radio\"/>" +
"<label for=\"radio8\">x9</label>" +
"</div>" +
"</form>" +
'</div> ');
NewDialog.dialog({
autoOpen: false,
modal: true,
height: 500,
width: 500,
title: 'Choose an image',
buttons: {
"Ok": function() {
$(this).dialog("close");
}
}
});
return false;
}​
You seem to have an unexpected 7 within your string which makes this concatenation invalid, causing a Uncaught SyntaxError: Unexpected string.
Change this:
"<label for=\"radio5\">x6</label>" + 7
"<input type=\"radio\" id=\"radio5\" name=\"radio\"/>" +
to either this:
"<label for=\"radio5\">x6</label>" +
"<input type=\"radio\" id=\"radio5\" name=\"radio\"/>" +
or this:
"<label for=\"radio5\">x6</label>" + 7 +
"<input type=\"radio\" id=\"radio5\" name=\"radio\"/>" +
In addition you need to set autoOpen to true if you want the dialog to be visible immediately.
DEMO - Removing the 7 and set autoOpen to true
You do not seem to be appending the HTML to the DOM to make it work..''
Append it to the body before you assign it to a Do=ialog and it should work..
var html = '<div id="imageSelectionDialog"> ' +
//other html ;
$('body').append(html);
var NewDialog = $("#imageSelectionDialog");
// Code to Initialize the dialog

Categories

Resources