javascript append from foreach loop not working - javascript

I am writing simple changelog for my website that uses github api and appends tag but it doesnt work.
this is my code:
<p id="testing"></p>
<script>
var c = document.getElementById("testing");
$.getJSON("https://api.github.com/repos/test234/test/releases").done(function (json) {
for each (release in json) {
c.appendChild(document.createTextNode(release.tag_name));
}
});
</script>
I think something is wrong with my foreach loop.
Any help is welcome I am stuck here for a long time

This is the right way to use forEach:
var c = document.getElementById("testing");
$.getJSON("https://api.github.com/repos/4u7157/DOWNLOADS/releases").done(function (json) {
json.forEach((e) => {
console.log(e);
c.appendChild(document.createTextNode(e.tag_name));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="testing"></p>
You can also use JQuery as follows:
var c = document.getElementById("testing");
$.getJSON("https://api.github.com/repos/4u7157/DOWNLOADS/releases").done(function (json) {
$.each(json, function( index, e ){
console.log(e);
c.appendChild(document.createTextNode(e.tag_name));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="testing"></p>

well, the reason is that your syntax is appropriate for arrays but here json is object so this syntax will not work unless you use Object.Entries
const entries = Object.entries(json)
for(const [index,obj] of entries){
c.appendChild(document.createTextNode(obj.tag_name))
}
or you can use for each method provided for objects like this :
json.forEach(function(value,key,obj){
c.appendChild(document.createTextNode(value.tag_name))
});
Rest is all good , you just need to look for these changes.

Related

Trying to build HTML elements by code, functions included

This is my first post, hoping someone can help me:
I wish to build a web project, where all the HTML elements are stored in database and taken from it to build the web page.
i found a problem with the buttons, i cannot find a way to store the function for a button, i´m using Jquery to build the elements, for now the test element definitions are simulated in some arrays i left at the start of my Js file, the only way i can make the buttons to work is if the functions are hardcoded in the Js file, is there a way for me to bring the functions from database too? and having them in an array?
this is my project sample:
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!--script src="functions.js"></script-->
<script src="system.js"></script>
<!--script src="elements.js"></script-->
</head>
<body>
<body onload="addElements()">
<div id="div1"></div>
</body>
</html>
JS File
/**
VARIABLE DEFINITIONS
THESE ARE SUPPOSED TO COME FROM A DATABASE
STILL UNKNOWN HOW TO BRING THE FUNCTIONS, AS STRING THEY ARE NOT ALLOWED. FOR NOW THERE ARE TEST FUNCTIONS.
**/
let buttonIds = ['btn1', 'btn2'];
let buttonText = ['Show Text', 'Show HTML'];
let buttonFunc = [alert1, alert2];
//let buttonFunc = ['alert("Hi");', 'alert("Hello");'];
let paragraphs = ['This is some <b>bold</b> text in a paragraph.', 'another <b>bold</b> test'];
//HELPER FUNCTIONS
// **** THESE ARE SUPPOSED TO COME FROM DATABASE, UNKNOWN HOW TO DO IT. ****
function alert1() {
alert("Hi");
}
function alert2(){
alert("Hello");
}
function addElements(){
for(var p=0; p<paragraphs.length; p++){ addParagraphs('#div1', paragraphs[p]); }
for(var i=0; i<buttonIds.length; i++) { createButton( '#div1', buttonIds[i] , buttonText[i]); }
}
// ANY ELEMENTS FUNCTION IS DEFINED HERE ONCE THE PAGE IS LOADED.
$(document).ready(function(){
for(var x=0;x<buttonIds.length; x++){ activateButton(buttonIds[x], buttonFunc[x]); }
});
//HELPER FUNCTIONS USED TO BUILD THE HTML ELEMENTS ON THE MAIN PAGE.
function addParagraphs(location, text){
$(location).append('<p id="test">'+text+'</p>');
}
function createButton(location, id, text){
var definition;
definition = "<button id="+id+">"+text+"</button>";
$(location).append(definition);
}
function activateButton(buttonId, functionName){
var composedId = "#"+buttonId;
$(composedId).click(functionName);
}
You can generate Javascript file serverside with all the funcions you need.
Supposing Node.js you can do something like this:
expressApp.get("some.js", (req, res) => {
getDataFromDatabase() // depends on your database
.then(data => {
let body = 'function your_fn () { alert("'+ JSON.stringify(data) +'")}';
res.send(body);
})
});
One approach is use an object to store the functions in javascript and use property names stored in db to associate which function to use for which element.
Without knowing more about your use case it is hard to really help design a proper system to use
Following is a very basic example
// functions stored in js file
const funcs = {
f1: function(e){ console.log('func one called , id = ', this.id)},
f2: function(e){ console.log('func 2 called , id = ', this.id)}
}
// data from database
const elems = [
{id: 1, className: 'one', func:'f1', text:'Item 1'},
{id: 1, className: 'two', func:'f2', text:'Item 2'}
]
elems.forEach(e => {
const $el= $('<div>', {id: e.id, class: e.className, text:e.text, click: funcs[e.func]})
$('body').append($el);
});
div {margin:1em;}
.one {color:red;}
.two {color:green;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<strong>Click on items</strong><br><br>

How to append Ajax Json respond to html?

I use ajax get a json like this:
{"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"}
How to append "delete_flag" , "id" , "icon_img" to 3 different places on html ?
You can use this pure javascript method like below.
The code basically uses document.getElementById() to get the element, and .innerHTML to set the inside of the element to the value of the object.
This code (and the code using jQuery) both use JSON.parse() to parse the data into the correct object that our code can read. The [0] at the end is to select the object we wanted since it would give us an array (and we want an object).
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
document.getElementById("delete_flag").innerHTML = parsedData.delete_flag;
document.getElementById("id").innerHTML = parsedData.id;
document.getElementById("icon_img").src = parsedData.icon_img;
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
Or you can use jQuery (which in my opinion, is much simpler). The code below uses .html() to change the inside of the divs to the item from the object, and .attr() to set the attribute src to the image source you wanted.
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
$("#delete_flag").html(parsedData.delete_flag);
$("#id").html(parsedData.id);
$("#icon_img").attr("src", parsedData.icon_img);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
you can use jQuery .html() or .text()
For example:
var json = {"id" : "74"};
$( "#content" )
.html( "<span>This is the ID: " + json.id + "</span>" );
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
Just use some simple JavaScript parsing:
const jsonData = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(jsonData.dataStore)[0];
document.getElementById("delFlag").textContent = "Delete Flag: " + parsedData["delete_flag"];
document.getElementById("id").textContent = "ID: " + parsedData["id"];
document.getElementById("img").textContent = "Image: " + parsedData["icon_img"];
<p id="delFlag"></p>
<p id="id"></p>
<p id="img"></p>
Note that you can't parse the full object jsonData because it's not JSON - only the data inside it is JSON.
I've upvoted the other answers, but maybe this will help someone else. On your ajax success function, do something like this:
success: function(data){
// console.log('succes: '+data);
var delete_flag = data['delete_flag'];
$('#results').html(delete_flag); // update the DIV or whatever element
}
if you got real fancy, you could create a for loop and put all the json variable you need into an array and create a function to parse them all into their proper elements; you could learn this on your own fairly easily.
var data = {
"dataStore": {
"delete_flag": "false",
id: "74"
}
}
$('.flag').html(data.dataStore.delete_flag);
$('.id').html(data.dataStore.id);
span {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Flag: <span class="flag"></span>
<hr />
ID: <span class="id"></span>

Linq with Javascript

i started work with LINQ in javascript using http://jslinq.codeplex.com/ where it is suggested to add package jslinq. I added it and started with following query
var exampleArray = JSLINQ(myList)
.Where(function(item){ return item.FirstName == "Chris"; })
.OrderBy(function(item) { return item.FirstName; })
.Select(function(item){ return item.FirstName; });
but while debugging, on first line (var exampleArray = JSLINQ(myList)) shown error like 'uncought reference error JSLINQ not defined'..
please inform me what i am missing.. i am completely new to this.. thanks in advance.
Have You added
<SCRIPT type="text/javascript" src="/scripts/JSLinq.js"></SCRIPT>
before you call JSLINQ(myList) ?

Automatic two way binding with Knockout

I'm just getting started with Knockout.js and i have a view(html) which is supposed to be populated by data from a rest api via jquery's $.getJSON method.
When i run the app, nothing shows but using firebug i can see that the 'GET' query returns a status code of 200 and the right data.
I'm at a fix as to why nothing shows in the view since the bindings in Knockout.js are supposed to be automatic.
Below is my code.
Thanks
<div id ='main'>
<!-- ko foreach: posts -->
<p>Hello</p><span data-bind="text: title"></span></p><p data-bind="text: content"></p>
<p data-bind="text: author"></p><p data-bind="text: date"></p>
<!-- /ko -->
</div>
</body>
<script type="text/javascript">
function Post(data){
this.title = ko.observable(data.title);
this.content = ko.observable(data.content);
this.author = ko.observable(data.author);
this.date = ko.observable(data.date)
}
function PostListViewModel(){
var self = this;
self.posts = ko.observableArray([]);
$.getJSON("/posts", function(getPost){
var mappedPost = $.map(getPost, function(item){
return new Post(item)
});
self.posts(mappedPost);
});
}
var postlistviewmodel = new PostListViewModel();
ko.applyBindings(postlistviewmodel);
</script>
This should be:
$.getJSON("/posts", function(getPost){
var mappedPosts = $.map(getPost, function(item){
return new Post(item)
});
self.posts(mappedPosts);
});
wouldn't do self.posts.push(mappedPosts[i]) at all. You should just pass mappedPosts through the ko binding in order to update the listeners.
If your just getting the latest posts and want to update your current list simply do:
var allPosts = self.posts().concat(mappedPosts);
self.posts(allPosts);
You don't need the model to have ko.observable if you're just displaying them. If you want to edit model as well, then leave as.
Also, I tend to do this for single or multiple view models:
ko.applyBindings({viewModel : new viewModel() };
This allows for having multiple named view models. Access scope using: $root.viewModel
This is what I did earlier: http://jsfiddle.net/jFb3X/
Check your code against this fiddle then.
Script tags also need to be above the closing body tags
<html>
<head>
</head>
<body>
<!-- all your html content -->
<script type="text/javascript">
var viewModel = function () {
}
ko.applyBindings({viewModel : new viewModel()});
</script>
</body>
</html>
Is it something as simple as waiting for the DOM to be ready?
Are you able to try the following:
$(function () {
ko.applyBindings(postlistviewmodel);
});
Source: I've done this a few times and been stumped for a bit trying to see what I did wrong. :-)
(As a style thing, I'd also move the /body to after the /script - probably not related to your issue though).
I suspect you get multiple posts from /posts. You only push a single item (array).
...
$.getJSON("/posts", function(getPost){
var mappedPosts = $.map(getPost, function(item){
return new Post(item)
});
for(var i = 0; i < mappedPosts.length; i++) {
self.posts.push(mappedPosts[i]);
}
});
...

Extracting value from JSON generated source code on a page

I have the below JSON data that is present in the source of our product detail pages (this is an ecommerce site).
I need to pull the "atrsell" value from each line using javascript/jquery.
Can somebody give me the bext way to do this please?
<script type="text/javascript">
$(document).ready(function(){
Attributes.StoreJSON({"att1":"Cobalt","att3":"","att2":"6","att4":""},{"atronhand":24,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"6","atrsku":"505274940925","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"30.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Cobalt","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Cobalt","att3":"","att2":"8","att4":""},{"atronhand":3430,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"8","atrsku":"505274940926","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"30.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Cobalt","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Cobalt","att3":"","att2":"14","att4":""},{"atronhand":50,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"14","atrsku":"505274940922","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"30.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Cobalt","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Emerald","att3":"","att2":"12","att4":""},{"atronhand":3,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"12","atrsku":"505274940942","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"42.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Emerald","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Emerald","att3":"","att2":"14","att4":""},{"atronhand":1,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"14","atrsku":"505274940943","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"42.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Emerald","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Emerald","att3":"","att2":"16","att4":""},{"atronhand":322,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"16","atrsku":"505274940944","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"42.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Emerald","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Emerald","att3":"","att2":"18","att4":""},{"atronhand":200,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"18","atrsku":"505274940945","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"42.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Emerald","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Navy","att3":"","att2":"10","att4":""},{"atronhand":431,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"10","atrsku":"505274940927","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"10.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Navy","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Phantom","att3":"","att2":"10","att4":""},{"atronhand":3443,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"10","atrsku":"505274940913","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"20.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Phantom","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Phantom","att3":"","att2":"12","att4":""},{"atronhand":99,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"12","atrsku":"505274940914","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"20.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Phantom","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Sweet Grape","att3":"","att2":"16","att4":""},{"atronhand":433,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"16","atrsku":"505274944584","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"68.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Sweet Grape","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
Attributes.StoreJSON({"att1":"Sweet Grape","att3":"","att2":"18","att4":""},{"atronhand":20,"atrreleaseyr":"1970","atrmsrp":"0.00","atrlbl3":null,"atr2":"18","atrsku":"505274944585","atr3":"","atrlbl4":null,"atrwas":"68.00","atr4":"","atrbarcode":"","atrsell":"68.00","atrlbl2":null,"atrsuplsku":"","atrreleasemn":"01","atretayr":"0001","invtuuid":"D72DCC08-A550-11E3-B4DF-EAD3DD919408","atrreleasedy":"01","atretady":"01","atr1":"Sweet Grape","atrdssku":"","atrmpncode":"","atretamn":"01","atrpublish":"1","atrcost":"0.00","atrlbl1":null});
});
</script>
Try
var arr = [],
Attributes = {
StoreJSON: function(obj1, obj2) {
arr.push(obj2);
}
};
/* Your code here*/
var atrsells = arr.map(function(i){
return i.atrsell;
});

Categories

Resources