How to get this data using the loop? - javascript

How do i show all the data by using the loop to display all the data from json to html ?
ATM , I am able to print one of the data. but if i am using data[i] the code will not display any data.
I think I mess up the the concept of object and array.
please advice me , how to loop thru object , like array?
thanks
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET','https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function () {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data.weather ){
var x= data.weather[i].main;
weatherString+= "<p class='weather'>" + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>

to get all data check for object and do recursive loop
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
//console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data) {
var x = data[i];
if(typeof(x) == "object") {
getHTML(x);
}
else {
weatherString += "<p class='weather'><b>" + i + "</b>: " + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>

var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for (var i in data.weather) {
var x = data.weather[i].main;
weatherString += "<p class='weather'>" + x + "</p>";
$.each(data.main, function(i, f) {
var main = "<div>" + i + ": " + f + "</div>";
$(main).appendTo("#main");
});
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
<div id="main"></div>

use foreach loop to iterate over all object
read more from here

Related

Remove() function doesnt work in firebase for web

This is the js file. What im trying to do is create an onclick delete function when clicked on a particular row in html page. So far i can get the child key(nesting) but somehow the delete function throws error i.e career-delete.html:1 Uncaught ReferenceError: MCu9V4ypS is not defined
at HTMLButtonElement.onclick (career-delete.html:1).
userImagesRef1.once("value", function(snapshot) {
var val1, val2, val3;
var ParentKey = snapshot.key;
console.log("PK"+ParentKey);
snapshot.forEach(function(childSnapshot) {
childSnapshot.forEach(function(snap){
var childKey = snap.key;
console.log("CK" + childKey);
var Vacancy = snap.child("VacancyNumber").val();
console.log("VacancyNumber" + Vacancy);
// var NoticeNumber = snap.child("Service").val();
// var NameofWork = snap.child("Title").val();
snap.child('pictures').forEach(function(openPicturesSnap){
console.log("KEY LINKS: " + openPicturesSnap.key);
// var i = 0;
if(openPicturesSnap.key == 0){
val1 = openPicturesSnap.val();
// console.log("LINKS1111::::" + val1 );
}
if(openPicturesSnap.key == 1){
val2 = openPicturesSnap.val();
}
if(openPicturesSnap.key == 3){
val1 = openPicturesSnap.val();
}
})
var Service = String(snap.child("Service").val());
// console.log(Service)
var ts = snap.child("timestamp").val();
// console.log("TS:" + ts);
var Title = String(snap.child("Title").val());
// console.log(Title)
let Numberofposts = String(snap.child("NumberofPosts").val());
// console.log(Numberofposts);
var SNo = "";
var State = snap.child("Status").val();
var IssueDate = snap.child("IssueDate").val();
var ClosingDate = snap.child("ClosingDate").val();
var Remarks = String(snap.child("Remarks").val());
$("#tableBody").append("<tr><td>"+ SNo +"</td><td><a href = '" + val1+ "'>" +Vacancy+"</a></td>"+ "<td><a href = '" +val2 + "'>" +Service+"</a></td><td>" + Title + "</td><td>"+Numberofposts+"</td><td>" + IssueDate + "</td><td>"+ClosingDate + "</td> <td>" + State+"<td><a href = '" +val3 + "'>" +Remarks+"</a>"+ "</td><td>"+'<button type="button" onClick=Delete('+childKey+'); class="btn delete">X</button>'+"</td></tr>" );
})
})
function Delete(key){
var feedRef = firebase.database().ref("user-images").child(key);
feedRef.remove()
.then(function(){
console.log("Remove succeeded.")
alert("Added");
// console.log(key.val());
})
.catch(function(error){
console.log("Remove Failed!"+error.message)
});
}
});
You can delete nodes by using the following alternative:
feedRef.set(null);
https://firebase.google.com/docs/database/web/read-and-write#delete_data
You need to add some double quotes as follows:
<button type="button" onclick="Delete('" +childKey+ "');" class="btn delete">X</button>

How to parse XML using AJAX in html?

I'm trying to parse XML by using AJAX. However there were a few errors which i got saying my "html is not defined"
Basically what I want to do is to parse a specific amount of data from my XML codes and display it using HTML webpage .
The below is the list of bugs in console when I tried to run the script
at displayCountrylist (test2.html:136)
at handleStatusSuccess (test2.html:61)
at readyStateChangeHandler (test2.html:32)
at XMLHttpRequest.xhttp.onreadystatechange (test2.html:16)
I tried to do everything to debug but still failed. Any one help please?
<html>
<script>
function makeAjaxQueryCountrylist()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
readyStateChangeHandler(xhttp);
};
xhttp.open("GET", "A3_CtryData_dtd_Sample.xml", true);
xhttp.send();
}
function readyStateChangeHandler(xhttp)
{
if (xhttp.readyState == 4)
{
if(xhttp.status == 200)
{
handleStatusSuccess(xhttp);
}else
{
handleStatusFailure(xhttp);
}
}
}
function handleStatusFailure(xhttp){
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
}
function handleStatusSuccess(xhttp)
{
var xml = xhttp.responseXML;
var countrylistObj = parseXMLCountrylist(xml);
displayCountrylist(countrylistObj);
}
function parseXMLCountrylist(xml)
{
var countrylistObj = {};
var countrylistElement = xml.getElementsByTagName("CountryList")[0];
var recordElementList = countrylistElement.getElementsByTagName("CountryRecord");
countrylistObj.recordList = parseRecordElementList(recordElementList);
return countrylistObj;
}
function parseRecordElementList(recordElementList)
{
var recordList = [];
for(var i=0; i < recordElementList.length; i++)
{
var recordElement = recordElementList[i];
var recordObj = parseRecordElement(recordElement);
recordList.push(recordObj);
}
return recordList;
}
function parseRecordElement(recordElement)
{
var recordObj = {};
var countrycodeElement = recordElement.getElementsByTagName("country-code")[0];
recordObj.countrycode = Number(countrycodeElement.textContent);
var nameElement = recordElement.getElementsByTagName("name")[0];
recordObj.name = nameElement.textContent;
var alpha2Element = recordElement.getElementsByTagName("alpha-2")[0];
recordObj.alpha2 = alpha2Element.textContent;
var alpha3Element = recordElement.getElementsByTagName("alpha-3")[0];
recordObj.alpha3 = alpha3Element.textContent;
var capitalcityElement = recordElement.getElementsByTagName("capital-city")[0];
recordObj.capitalcity = capitalcityElement.textContent;
return recordObj;
}
function displayCountrylist(countrylistObj)
{
for(var i=0; i < countrylistObj.recordList.length; i++)
{
var recordObj = countrylistObj.recordList[i];
html += "country-code: " + recordObj.countrycode;
html += "<br />";
html += "name: " + recordObj.name;
html += "<br />";
html += "alpha-2: " + recordObj.alpha2;
html += "<br />";
html += "alpha-3: " + recordObj.alpha3;
html += "<br />";
html += "capital-city: " + recordObj.capitalcity;
html += "<br />";
}
var displayDiv = document.getElementById("display1");
displayDiv.innerHTML = html;
}
</script>
<body>
<button onClick="makeAjaxQueryCountrylist()"> Region Info I (Format: region-fmt-1.xsl)</button>
<br /><br />
<div id="display1">
</div>
</body>
</html>
There isn't any problem with my XML codes so it has to be some error from here.
You got that error html is not defined because you are using html variable without declaring it. So, before the line
html += "country-code: " + recordObj.countrycode;
you have to write
let html = '';

address book using json html javascript

I am working on Address book using HTML,CSS and Javascript. First I am reading some data entries from a JSON file. Then storing those entries into local storage. Then I am taking input from the user in few input fields through the function called addToBook(). And then storing all the data in JSON format in the variable called addressBook. But when i am trying to print this data in the function called showaddressBook(). It is not happening as it is showing as Undefined in the chrome console. Refer to this line(console.log(addressBook[i].practice_name);) in the function showaddressBook(). Any idea guys. Thanks in advance.
window.onload = function(){
var quickAddFormDiv = document.querySelector('.quickaddForm');
var AddBtn = document.getElementById('Add');
// Form Fields
var lastname = document.getElementById('lastname');
var firstname = document.getElementById('firstname');
var email = document.getElementById('email');
var specialty = document.getElementById('specialty');
var practicename = document.getElementById('practicename');
// Divs etc.
var addBookDiv = document.querySelector('.addbook');
var addressBook = [];
var people;
localStorage.clear();
//--------------------------------------------------------------------
//To display the contents of JSON file
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
people = response.people;
//var output = "";
var str1 = '';
for(var i = 0; i <people.length;i++){
str1 += '<div id="entry">';
str1 += '<div id="name"><p>' + people[i].last_name +', '+people[i].first_name+ '</p></div>';
str1 += '<div id="email"><p>' + people[i].email_address + '</p></div>';
str1 += '<div id="practicename"><p>' + people[i].practice_name + '</p></div>';
str1 += '<div id="specialty"><p>' + people[i].specialty + '</p></div>';
str1 += '<div id="del">Delete</div>';
}
for(var i = 0; i < people.length;i++){
var obj = new jsonStructure(people[i].last_name,people[i].first_name,people[i].email_address,people[i].specialty,people[i].practice_name);
addressBook.push(obj);
localStorage['addbook'] = JSON.stringify(addressBook);
}
document.getElementsByClassName("addbook")[0].innerHTML = str1;
}
};
xhttp.open("GET", "people.json", true);
xhttp.send();
//------------------------------------------------------------------------------
AddBtn.addEventListener("click", addToBook);
//var addressBook = [];
addBookDiv.addEventListener("click", removeEntry);
function jsonStructure(lastname,firstname,email,specialty,practicename){
this.lastname = lastname;
this.lastname += ", "+firstname;
this.email = email;
this.specialty = specialty;
this.practicename = practicename;
}
function addToBook(){
var isNull = lastname.value!='' && firstname.value!='' && email.value!='' && specialty.value!='' && practicename.value!='';
if(isNull){
// format the input into a valid JSON structure
var obj = new jsonStructure(lastname.value,firstname.value,email.value,specialty.value,practicename.value);
addressBook.push(obj);
localStorage['addbook'] = JSON.stringify(addressBook);
console.log(localStorage['addbook']);
clearForm();
showaddressBook();
}
}
function removeEntry(e){
// Remove an entry from the addressBook
if(e.target.classList.contains('delbutton')){
var remID = e.target.getAttribute('data-id');
addressBook.splice(remID,1);
localStorage['addbook'] = JSON.stringify(addressBook);
showaddressBook();
}
}
function clearForm(){
var formFields = document.querySelectorAll('.formFields');
for(var i in formFields){
formFields[i].value = '';
}
}
function showaddressBook(){
if(localStorage['addbook'] === undefined){
localStorage['addbook'] = '';
} else {
addressBook = JSON.parse(localStorage['addbook']);
addBookDiv.innerHTML = '';
var str = '';
for(var i = 0; i <addressBook.length;i++){
str += '<div id="entry">';
str += '<div id="name"><p>' + addressBook[i].last_name +', '+addressBook[i].first_name+ '</p></div>';
str += '<div id="email"><p>' + addressBook[i].email_address + '</p></div>';
str += '<div id="practicename"><p>' + addressBook[i].practice_name + '</p></div>';
str += '<div id="specialty"><p>' + addressBook[i].specialty + '</p></div>';
str += '<div id="del">Delete</div>';
console.log(addressBook[i].practice_name);
}
}
}
showaddressBook();
}
There are typo mistakes,
practice_name should be practicename
last_name should be lastname
first_name should be firstname
email_address should be email
Try:
for(var i = 0; i <addressBook.length;i++){
str += '<div id="entry">';
str += '<div id="name"><p>' + addressBook[i].lastname +', '+addressBook[i].firstname+ '</p></div>';
str += '<div id="email"><p>' + addressBook[i].email + '</p></div>';
str += '<div id="practicename"><p>' + addressBook[i].practicename + '</p></div>';
str += '<div id="specialty"><p>' + addressBook[i].specialty + '</p></div>';
str += '<div id="del">Delete</div>';
console.log(addressBook[i].practicename);
}

JavaScript: Remove Double Quotes - JSON.Stringify()

After using he JSON.stringify() method in JavaScript to allow JSON data render in the browser it outputs double quotations " " at either end of the property rendered in the browser - any idea how to resolve this?
Here is my code -
<li class="divider">Brown Eyes</li>
<div id="output1"></div>
<li class="divider">Green Eyes</li>
<div id="output2"></div>
<script>
var myContainer = "";
var a = new XMLHttpRequest();
a.open("GET", "https://api.myjson.com/bins/1dwnm", true);
a.onreadystatechange = function () {
console.log(a);
if (a.readyState == 4) {
var obj = JSON.parse(a.responseText);
for (i = 0; i < obj.length; i++) {
if (obj[i].eyeColor == 'brown') {
var myContainer = "<ul class='list'><li>" + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + "</li></ul>";
var myContainer = JSON.stringify(myContainer);
document.getElementById('output1').innerHTML += myContainer;
}
if (obj[i].eyeColor == 'green') {
var myContainer = "<ul class='list'><li>" + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + "</li></ul>";
var myContainer = JSON.stringify(myContainer);
document.getElementById('output2').innerHTML += myContainer;
}
}
}
}
a.send();
</script>
Because "<ul class='list'><li>Faye Garrett - brown</li></ul>" is not a valid JSON string.
Uncomment your stringify lines and it works.

I need Javascript syntax and logic advice

I have a two part question. The first is that I tried to replace all of my document.write with innerHTML and now nothing generates on the page correctly. The second part of my question is that I can't figure out the logic on my toggleCurrent function so that I can hide show the currently displayed view. example - if the thumbnail view is visible I want to hide/show or if the full view is visible I want to hide/show that. http://jsfiddle.net/5M3k7/
//Creating generic Object
function Person(name,age,biog,thumb,char,bg,cider) {
this.fullName = name;
this.age = age;
this.biog = biog;
this.thumb = thumb;
this.char = char;
this.bg = bg;
this.cider = cider;
}
//Creating new Objects
var jay = new Person ("Jay Jones",24,"Story","img","guy","bg","Fleet",true);
var jai = new Person ("Jai Janes",23,"Story","img","gal","bg","Sleet",true);
var dan = new Person ("Dan Dones",19,"Story","img","guy","bg","Leet",true);
var den = new Person ("Den Danes",49,"Story","img","guy","bg","Treat",true);
var dun = new Person ("Dun Dunes",20,"Story","img","guy","bg","Meet",true);
var vim = new Person ("Vim Vanes",22,"Story","img","guy","bg","Meat",true);
//Defining arrays
var characters = [jay, jai, dan, den, dun, vim];
//For loop goes though character array and prints it out.
var thumbs = function() {
var full = document.getElementById('full');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
}
return;
};
var full = function() {
var thumb = document.getElementById('fullthumb');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
thumb.innerHTML = '<div class="fullwrap"><div class="bg"><div class="fullcont">Name: '
+ characters[i].fullName + '<br/> Age:' + characters[i].age + '<br/>Cider:' + characters[i].cider + '<div class="char"></div></div></div></div>';
}
return;
};
//Toggle Function
function toggleMenuDiv() {
var full = document.getElementById('full');
var thumb = document.getElementById('fullthumb');
var butt = document.getElementById('button');
if (full.style.display == 'none') {
full.style.display = 'block';
thumb.style.display = 'none';
butt.innerHTML = 'THUMB VIEW<span class="arrow-e"></span>';
}
else {
full.style.display = 'none';
thumb.style.display = 'block';
butt.innerHTML = 'FULL VIEW<span class="arrow-e"></span>';
}
}
//Toggle Function
function toggleCurrent() {
var chng = document.getElementById('change');
var thumb = document.getElementById('fullthumb');
var full = document.getElementById('full');
while (full.style.display == 'none')
{
if(thumb.style.display == 'block') {
chng.innerHTML = 'HIDE<span class="arrow-n"></span>';
}else{
thumb.style.display = 'none';
chng.innerHTML = 'SHOW<span class="arrow-s"></span>';
}
}
}
Because you keep overriding the last thing entered in.
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
You are need to append to the innerHTML
full.innerHTML = full.innerHTML + '<div class="...

Categories