How to Gather & Parse JSON Data in HTML - javascript

I'm ultimately looking to create a HTML file that will accomplish the following tasks. The point is, I need it to be all inclusive in an HTML snippet/file.
Make a GET api call to a backend CMS (ie: Drupal). This api call returns the following JSON data for a specific content item:
{
"jsonapi": {
"version": "1.0",
"meta": {
"links": {
"self": {
"href": "http://jsonapi.org/format/1.0/"
}
}
}
},
"data": {
"type": "node--espot_html",
"id": "fbaab7dd-09c2-4aa0-852d-4b9462074a45",
"attributes": {
"drupal_internal__nid": 1,
"drupal_internal__vid": 11,
"langcode": "en",
"revision_timestamp": "2019-10-31T13:29:29+00:00",
"revision_log": null,
"status": true,
"title": "Razor Hero Image",
"created": "2019-10-28T16:24:20+00:00",
"changed": "2019-10-31T13:29:29+00:00",
"promote": true,
"sticky": false,
"default_langcode": true,
"revision_translation_affected": true,
"path": {
"alias": "/razor-hero",
"pid": 1,
"langcode": "en"
},
"body": {
"value": "<div class=\"jns-hero-image jns-hero-image-message-left\" id=\"hero_slideshow\"><img alt=\"Clean Shave\" data-entity-type=\"file\" data-entity-uuid=\"fbc875d0-ef17-4813-981c-22a29e42c44f\" src=\"/sites/default/files/inline-images/dont-shave-2.jpg\" />\r\n<div class=\"grid-container\">\r\n<div class=\"grid-x grid-padding-x\">\r\n<div class=\"small-12 medium-8 cell hero-message\">\r\n<div>\r\n<h1 class=\"text-hero text-hero-left\">Get a Much Better<br />\r\nShave</h1>\r\n\r\n<p>Fewer things look and feel better than a clean shave!</p>\r\n<a>SHOP NOW</a></div>\r\n</div>\r\n</div>\r\n</div>\r\n</div>\r\n",
"format": "full_html",
"processed": "<div class=\"jns-hero-image jns-hero-image-message-left\" id=\"hero_slideshow\"><img alt=\"Clean Shave\" data-entity-type=\"file\" data-entity-uuid=\"fbc875d0-ef17-4813-981c-22a29e42c44f\" src=\"/sites/default/files/inline-images/dont-shave-2.jpg\" /><div class=\"grid-container\">\n<div class=\"grid-x grid-padding-x\">\n<div class=\"small-12 medium-8 cell hero-message\">\n<div>\n<h1 class=\"text-hero text-hero-left\">Get a Much Better<br />\nShave</h1>\n\n<p>Fewer things look and feel better than a clean shave!</p>\n<a>SHOP NOW</a></div>\n</div>\n</div>\n</div>\n</div>\n",
"summary": ""
}
},
"relationships": {
"node_type": {
"data": {
"type": "node_type--node_type",
"id": "837a5cbe-f8fe-4c03-a613-2092dff1168e"
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/relationships/node_type?resourceVersion=id%3A11"
},
"related": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/node_type?resourceVersion=id%3A11"
}
}
},
"revision_uid": {
"data": {
"type": "user--user",
"id": "c0d80edb-325a-4ad7-9be3-bc9dc32ed878"
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/relationships/revision_uid?resourceVersion=id%3A11"
},
"related": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/revision_uid?resourceVersion=id%3A11"
}
}
},
"uid": {
"data": {
"type": "user--user",
"id": "c0d80edb-325a-4ad7-9be3-bc9dc32ed878"
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/relationships/uid?resourceVersion=id%3A11"
},
"related": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45/uid?resourceVersion=id%3A11"
}
}
}
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45?resourceVersion=id%3A11"
}
}
},
"links": {
"self": {
"href": "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45"
}
}
}
I'm then looking for the JSON response to be parsed to extract the only the data under the "value": object.
I need to have the escape characters removed
The end result should be that the HTML (shown below) is rendered in the browser:
<div class="jns-hero-image jns-hero-image-message-left" id="hero_slideshow"><img alt="Clean Shave" data-entity-type="file" data-entity-uuid="fbc875d0-ef17-4813-981c-22a29e42c44f" src="/sites/default/files/inline-images/dont-shave-2.jpg" /><div class="grid-container"><div class="grid-x grid-padding-x"><div class="small-12 medium-8 cell hero-message"><div><h1 class="text-hero text-hero-left">Get a Much Better<br />Shave</h1><p>Fewer things look and feel better than a clean shave!</p><a>SHOP NOW</a></div></div></div></div></div>"
If processed successfully, this is what should display on the webpage:
Screenshot if image rendered via HTML
Here is the HTML I have tried. My apologies for breaking etiquette, I was not aware this would be perceived as such. In my browsers console it tells me the forEach is not a valid function or this response.
'<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ghibli App</title>
<link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet" />
<!-- <link href="style.css" rel="stylesheet" /> -->
</head>
<body>
<div id="root"></div>
<script>
const app = document.getElementById('root');
const container = document.createElement('div');
container.setAttribute('class', 'container');
app.appendChild(logo);
app.appendChild(container);
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45', true);
request.onload = function () {
// Begin accessing JSON data here
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
data.forEach(value => {
const card = document.createElement('div');
card.setAttribute('class', 'card');
const h1 = document.createElement('h1');
h1.textContent = valuable.title;
const p = document.createElement('p');
value.description = value.description.substring(0, 300);
p.textContent = `${value.description}...`;
container.appendChild(card);
card.appendChild(h1);
card.appendChild(p);
});
} else {
const errorMessage = document.createElement('marquee');
errorMessage.textContent = `Gah, it's not working!`;
app.appendChild(errorMessage);
}
}
request.send();
</script>
</body>
</html>'

This ended up producing the end result that I was looking to produce:
<!DOCTYPE html>
<html>
<body>
<div id="root"></div>
<script>
const app = document.getElementById('root');
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let obj = JSON.parse(this.responseText);
console.log(obj.data.attributes.body.value)
app.innerHTML = obj.data.attributes.body.value.replace('src="/sites','src="http://localhost:4700/sites');
}
};
xmlhttp.open("GET", "http://localhost:4700/jsonapi/node/espot_html/fbaab7dd-09c2-4aa0-852d-4b9462074a45", true);
xmlhttp.send();
</script>
</body>
</html>

Related

Calling REST API with bearer token and fetch url

I am a beginner in javascript
I'm here to learn there can be mistakes in my code.
I made a rest api in express.js that distributes pokemons for example.
It works perfectly and it is online.
I made all the tests of different accesses GET/POST, AUTH/TOKEN with postman with success.
step 1:
to access this API
I connect successfully from my page "index.html" which calls a .js file in which I "fetch" the url : https://myDomain/api/login with a "bearer token
step 2 :
From "index.html" I can access my list of objects with the div : "#content".
step 3:
From this list, I want to be able to click on one of the elements to display this object in detail to the div : "#output"
for the moment I have created an input in which I fill in the "id" as "value" of the object and when I click on it I display it with the "fetchList" function
it works.
If I try to create this input from my "for loop" (it is my target) I get a token refusal.
I do not understand why it works outside the "for loop" and not inside
can you guide me ?
I am really blocked
thanks in advance
my js :
// Create html container
const container = document.createElement('div');
container.setAttribute('class', 'container');
output.appendChild(container);
// Create html Card element
const card = document.createElement('div');
card.setAttribute('class', 'card-single');
container.appendChild(card);
// Create html object header
const h1 = document.createElement('h1');
h1.setAttribute('class', 'header');
h1.setAttribute('id', 'header');
// Create date
const createdAt = document.createElement('p');
createdAt.setAttribute('class', 'date');
//==================================≠≠≠≠≠====================≠≠≠≠≠≠≠≠
// Step 1 : "Get JWT token
//==================================≠≠≠≠≠====================≠≠≠≠≠≠≠≠
fetch("https://myDomain/api/login", {
method: "POST",
body: JSON.stringify({ username: "username", password: "password" }),
headers: { "Content-type": "application/json" }
})
.then((res) => res.json())
.then((res) => {
console.log(res);
return res.token;
})
.then((token) => {
fetchlist(token)
$('.clickMe').click(function(){
// alert(this.id);
fetchSingle(token)
});
});
//==================================≠≠≠≠≠====================≠≠≠≠≠≠≠≠
// Step 2 : "Get Object list
//==================================≠≠≠≠≠====================≠≠≠≠≠≠≠≠
const fetchlist = (token) => {
const baseUrl = "https://myDomain/api/pokemons/"
try {
fetch(baseUrl, {
headers: {Authorization: `Bearer ${token}`}
})
.then((response) => {
if (response.status == 200) {
// alert ("json ok");
// console.log(response);
return response.json();
} else {
throw new Error("NETWORK RESPONSE ERROR");
}
})
.then((poke) => {
displayList(poke);
})
.catch(error => {
console.error(error)
});
} catch (error) {
console.error(error)
}
const contentDiv = document.getElementById("content");
const container = document.createElement('div');
container.setAttribute('class', 'container');
contentDiv.appendChild(container);
container.insertAdjacentHTML('beforebegin',
// BELOW IS MY INPUT OUTSIDE FOR LOOP [WORKING FINE!]
`
<!-- <input type="text" onclick="fetchSingle();" class="clickMe" placeholder="id?">-->
`
)
function displayList(poke) {
for (let i in poke.data) {
let z = poke.data[i];
// console.log("Z :" + z);
// Create html for Card element
const card = document.createElement('div');
card.setAttribute('class', 'card');
container.appendChild(card);
card.insertAdjacentHTML('beforeend',
// BELOW IS MY INPUT INSIDE FOR LOOP [NOT WORKING]
`
<input type="text" value="${z.id}" onclick="fetchSingle();" class="clickMe">
`
)
// Create html for object name
const h1 = document.createElement('h1');
h1.setAttribute('class', 'header');
// h1.textContent = z.name;
h1.innerHTML = z.name;
card.appendChild(h1);
}
}
}
//==================================≠≠≠≠≠====================≠≠≠≠≠≠≠≠
// Step 3 : "Get Single Object
//==================================≠≠≠≠≠====================≠≠≠≠≠≠≠≠
const fetchSingle = (token) => {
const myid = event.srcElement.value;
console.log("Myid : " + myid );
try {
fetch("https://myDomain/api/pokemons/" + myid, {
headers: {Authorization: `Bearer ${token}`}
})
// alert(token)
// alert(myid)
.then((singleresponse) => {
if (singleresponse.status == 200) {
// alert ("json ok");
// console.log(singleresponse.json());
return singleresponse.json();
} else {
throw new Error("NETWORK RESPONSE ERROR");
}
})
.then((single) => {
if (!myid) {
console.log("data null");
// alert("data null");
} else {
// alert("data ok")
displaySingle(single);
}
})
.catch(error => {
console.error(error)
});
} catch (error) {
console.error(error)
}
function displaySingle(single) {
const poke = single.data;
// update name
h1.textContent = poke.name;
card.appendChild(h1);
// single object update date
const event = new Date(poke.created);
createdAt.textContent = "Created at : " + event.toLocaleString(undefined, {timeZone: 'UTC'});
card.appendChild(createdAt);
}
}
My html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Fetch & display API data using JavaScript</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<main>
<h1>Single result view </h1>
<div id="output"></div>
<h1>List view</h1>
<div id="content"></div>
</main>
<script src="file.js"></script>
</body>
</html>
Json data
{
"message": "La liste des pokémons a bien été récupérée.",
"data": [
{
"types": [
"Poison"
],
"id": 8,
"name": "Abo",
"hp": 16,
"cp": 4,
"picture": "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/023.png",
"created": "2022-07-15T12:41:44.000Z"
},
{
"types": [
"Insecte",
"Poison"
],
"id": 5,
"name": "Aspicot",
"hp": 16,
"cp": 2,
"picture": "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/013.png",
"created": "2022-07-15T12:41:44.000Z"
},
{
"types": [
"Plante",
"Poison"
],
"id": 1,
"name": "Bulbizarre",
"hp": 25,
"cp": 5,
"picture": "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/001.png",
"created": "2022-07-15T12:41:44.000Z"
},
{
"types": [
"Eau"
],
"id": 3,
"name": "Carapuce",
"hp": 21,
"cp": 4,
"picture": "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/007.png",
"created": "2022-07-15T12:41:44.000Z"
},
{
"types": [
"Feu"
],
"id": 12,
"name": "Groupix",
"hp": 17,
"cp": 8,
"picture": "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/037.png",
"created": "2022-07-15T12:41:44.000Z"
},
{
"types": [
"Fée"
],
"id": 11,
"name": "Mélofée",
"hp": 25,
"cp": 5,
"picture": "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/035.png",
"created": "2022-07-15T12:41:44.000Z"
},
{
"types": [
"Normal",
"Vol"
],
"id": 7,
"name": "Piafabec",
"hp": 14,
"cp": 5,
"picture": "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/021.png",
"created": "2022-07-15T12:41:44.000Z"
},
{
"types": [
"Electrik"
],
"id": 9,
"name": "Pikachu",
"hp": 21,
"cp": 7,
"picture": "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/025.png",
"created": "2022-07-15T12:41:44.000Z"
},
{
"types": [
"Normal"
],
"id": 6,
"name": "Rattata",
"hp": 18,
"cp": 6,
"picture": "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/019.png",
"created": "2022-07-15T12:41:44.000Z"
},
{
"types": [
"Normal",
"Vol"
],
"id": 4,
"name": "Roucool",
"hp": 30,
"cp": 7,
"picture": "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/016.png",
"created": "2022-07-15T12:41:44.000Z"
},
{
"types": [
"Normal"
],
"id": 10,
"name": "Sabelette",
"hp": 19,
"cp": 3,
"picture": "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/027.png",
"created": "2022-07-15T12:41:44.000Z"
},
{
"types": [
"Feu"
],
"id": 2,
"name": "Salamèche",
"hp": 28,
"cp": 6,
"picture": "https://assets.pokemon.com/assets/cms2/img/pokedex/detail/004.png",
"created": "2022-07-15T12:41:44.000Z"
}
]
}
You forgot to declare two variables in your javascript file. Which at least brings the code you posted to error.
In the displayList function the variables i and z are never declared. This probably causes your error.
Change it like this:
for (let i in poke.data) {
let z = poke.data[i];
Like this, it works for me. Not sure if there are more problems with your code.
I recommend you change your service's username and password after posting it on StackOverflow

Dynamically generate innerHTML elements from a response array (Javascript)

I'm a novice using JavaScript syntax and am having trouble adapting any solutions I find to match this.
This is a part of my code:
var arr1 = response;
console.log(arr1);
**This is the response/console logged arr1:
{
"channels": {
"1620184778889x527731420801269760": [
{
"channel": "1620184778889x527731420801269760",
"timetoken": "16204064644032062",
"message": {
"content": "44444444444",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
],
"1618599897203x154294096401530880": [
{
"channel": "1618599897203x154294096401530880",
"timetoken": "16203351496721278",
"message": {
"content": "fffffffdd",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
],
"1618613571551x955443898854408200": [
{
"channel": "1618613571551x955443898854408200",
"timetoken": "16204261556065826",
"message": {
"content": "78777",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
]
}
}
Trying to:
I need to get the following data:
1.channel
2.timetoken
3.message > content
4.message > sender
And then I need to dynamically generate an innerHTML property for each channel in the array (the amount of channels will frequently vary).
Something like this for each channel returned (incorrect syntax, just an example):
document.getElementById(channel).innerHTML = sender + ' ' + content + ' ' + timetoken;
I am having difficulty adapting other similar solutions to retrieve the nested array items and use loops. I think I need a loop to go through the channels to retrieve the data and also a loop to generate the innerHTML items, but I have been trying for days and can't get it, I am hoping someone well versed can assist.
Thank you.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
</body>
</html>
<script>
let dataObject = {
"channels": {
"1620184778889x527731420801269760": [
{
"channel": "1620184778889x527731420801269760",
"timetoken": "16204064644032062",
"message": {
"content": "44444444444",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
],
"1618599897203x154294096401530880": [
{
"channel": "1618599897203x154294096401530880",
"timetoken": "16203351496721278",
"message": {
"content": "fffffffdd",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
],
"1618613571551x955443898854408200": [
{
"channel": "1618613571551x955443898854408200",
"timetoken": "16204261556065826",
"message": {
"content": "78777",
"sender": "Jeremy"
},
"messageType": null,
"uuid": "1617237881603x986210451354598100"
}
]
}
}
for (let channelName in dataObject.channels) {
for (let item of dataObject.channels[channelName]) {
const channel = item.channel;
const timetoken = item.timetoken;
const content = item.message.content;
const sender = item.message.sender;
const messageType = item.messageType;
const uuid = item.uuid;
// do whatever you want with these data
console.log(channel, timetoken, content, sender, messageType, uuid);
}
}
</script>

List on json file

I have a problem with the list on json file data.
i want to catch the informations from json file and insert these in list.
HTML :
<ol id="dataT">
</ol>
JavaScript :
function GetData(index) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
ShowJson(this.responseText);
}
};
var counter;
switch (index) {
case "1":
counter = "./data/data1.json";
break;
case "2":
counter = "./data/data2.json";
break;
case "3":
counter = "./data/data3.json";
break;
default:
counter = "./data/data1.json";
}
xhttp.open("GET", counter, true);
xhttp.send();
}
function ShowJson(JsonData) {
var obj = JSON.parse(JsonData);
document.getElementById("dataT").innerHTML = obj.dataT;
}
Json file data:
"dataT" : {"tag":"ol","children":[
{"tag":"li","html":"Please Love Me"},
{"tag":"li","html":"You Upset Me Baby"},
{"tag":"li","html":"Everyday I Have The Blues"},
{"tag":"li","html":"Bad Luck"},
{"tag":"li","html":"3 O'Clock Blues"},
{"tag":"li","html":"Blind Love"},
{"tag":"li","html":"Woke Up This Morning"},
{"tag":"li","html":"You Know I Love You"},
{"tag":"li","html":"Sweet Little Angel"},
{"tag":"li","html":"Ten Long Years"},
{"tag":"li","html":"Did You Ever Love A Woman"},
{"tag":"li","html":"Crying Won't Help You"}
]}
In this moment, the result is : [object Object].
You can't directly assign data to innerHTML like 'document.getElementById("dataT").innerHTML = obj.dataT;' as you have done in your code.
You have to iterate through your data obj to bind list items one by one like:
function bindData() {
var myData = {
"dataT": {
"tag": "ol",
"children": [{
"tag": "li",
"html": "Please Love Me"
},
{
"tag": "li",
"html": "You Upset Me Baby"
},
{
"tag": "li",
"html": "Everyday I Have The Blues"
},
{
"tag": "li",
"html": "Bad Luck"
},
{
"tag": "li",
"html": "3 O'Clock Blues"
},
{
"tag": "li",
"html": "Blind Love"
},
{
"tag": "li",
"html": "Woke Up This Morning"
},
{
"tag": "li",
"html": "You Know I Love You"
},
{
"tag": "li",
"html": "Sweet Little Angel"
},
{
"tag": "li",
"html": "Ten Long Years"
},
{
"tag": "li",
"html": "Did You Ever Love A Woman"
},
{
"tag": "li",
"html": "Crying Won't Help You"
}
]
}
};
for (var i in myData.dataT.children) {
var node = document.createElement("LI");
var textnode = document.createTextNode(myData.dataT.children[i].html);
node.appendChild(textnode);
document.getElementById("dataT").appendChild(node);
}
}
<ol id="dataT"></ol>
<button onclick="bindData()">Bind Data</button>

How can I do conditional rendering with Mustache JS?

Here's how my data looks exactly, coming back from the server:
[
{
"sprout-framework": {
"state": {
"string": "Activate",
"decision": "activate"
},
"data": [
{
"name": "Sprout Framework",
"slug": "sprout-framework",
"source": "C:\\xampp\\htdocs\\wordpress/wp-content/themes/amaranth/Includes/Plugins/sprout-framework.zip",
"required": true,
"version": "1.0",
"force_activation": false,
"force_deactivation": false,
"external_url": "",
"is_callable": "",
"file_path": "sprout-framework/index.php",
"source_type": "bundled"
}
]
}
},
{
"elementor": {
"state": {
"string": "Install",
"decision": "install"
},
"data": [
{
"name": "Elementor",
"slug": "elementor",
"source": "C:\\xampp\\htdocs\\wordpress/wp-content/themes/amaranth/Includes/Plugins/elementor.2.1.6.zip",
"required": false,
"version": "2.1.6",
"force_activation": false,
"force_deactivation": false,
"external_url": "",
"is_callable": "",
"file_path": "elementor",
"source_type": "bundled"
}
]
}
}
]
For each one of these items, I render a <li> containing the details but depending on its [key].state.decision, I might choose to render it different or even show some buttons. For example, if an item comes back with the state.decision: activate back, I will have to hide the install button and instead show the activate one.
I'm currently rendering (using an older version of Mustache) as such:
/**
*
* #param {*} pluginsData
*/
const generateRequriedPluginsMarkup = (pluginsData) => {
const allPluginsTemplate = $('#plugins-to-install-list');
const individualPluginTemplate = $('#plugins-to-install-item');
let html = '';
for(let i = 0; i < pluginsData.length; i++) {
for(const property in pluginsData[i]) {
if (pluginsData[i].hasOwnProperty(property)) {
html += mustache(individualPluginTemplate.html(), {
'pluginSlug': pluginsData[i][property].data[0].slug,
'pluginState': pluginsData[i][property].state.decision,
'pluginName': pluginsData[i][property].data[0].name,
'translatedText_installPlugin': 'Install',
'translatedText_activatePlugin': 'Activate'
});
}
}
}
html = mustache(allPluginsTemplate.html(), {
plugins: html
});
return html;
}
With the Mustache templates being:
<!-- Plugins to Install -->
<script type="template/mustache" id="plugins-to-install-list">
<ul id="plugins-to-install-list">
{{{plugins}}}
</ul>
</script>
<!-- Plugins to Install Item-->
<script type="template/mustache" id="plugins-to-install-item">
<li id="install-plugin-{{{pluginSlug}}}" class="plugin-to-install" data-state="{{{pluginState}}}" data-failed="no" data-installed="no" data-activated="no">
<h4 class="plugin-name">{{{pluginName}}}</h4>
<div class="plugin-buttons">
<button class="install-plugin">{{{translatedText_installPlugin}}}</button>
<button class="activate-plugin hidden">{{{translatedText_activatePlugin}}}</button>
</div>
</li>
</script>
Is this possible?

Delete Entry from jstree does not works

I have 2 jstree.
from 1st tree i am sending selectd nodes to 2nd tree.
on back button I am deleting entry of 2nd tree with its id but it doesnot works but it fetches all the selected records.
here is my code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<style>
html { margin:0; padding:0; font-size:62.5%; }
body { font-size:14px; font-size:1.4em; }
h1 { font-size:1.8em; }
.demo { overflow:auto; border:1px solid silver; min-height:100px;min-width: 400px;float: left }
.demo1 { overflow:auto; border:1px solid silver; min-height:100px;min-width: 400px; float: right}
</style>
<link rel="stylesheet" href="style.min.css" />
</head>
<body><div id="frmt" class="demo"></div>
<div id="frmt1" class="demo1"></div>
<script>
var arrayCollection = [ {"id": "animal", "parent": "#", "text": "Animals"}, {"id": "device", "parent": "#", "text": "Devices"}, {"id": "dog", "parent": "animal", "text": "Dogs"}, {"id": "lion", "parent": "animal", "text": "Lions"}, {"id": "mobile", "parent": "device", "text": "Mobile Phones"}, {"id": "lappy", "parent": "device", "text": "Laptops"}, {"id": "daburman", "parent": "dog", "text": "Dabur Man", "icon": "/"}] ;
</script>
<script>
function refreshJSTree() {
$('#frmt1').jstree(true).settings.core.data = arrayCollection;
$('#frmt1').jstree(true).refresh();
}
</script>
<script>
function deleteNode() {
console.log("Delete : "+$('#frmt1').jstree("get_checked"));
arrayCollection = arrayCollection.pop($('#frmt1').jstree("get_checked"));/*
.filter(function(el) {
return el.id !== $('#frmt1').jstree("get_checked");
});*/
refreshJSTree();
}
</script>
<script>
function callGraph() {
var akn=$('#frmt').jstree("get_checked");
var c = akn + "";
var spl = c.split("!");
var dt = "";
var cnt = spl.length - 1;
arrayCollection=[];
var temp=[];
console.log("SPL : "+spl);
for(q=0;q<cnt;q++)
{
if (spl[q].startsWith(","))
{
var xp=spl[q].split(",")[1];
if(xp.startsWith("OU") || spl[q].startsWith("DC"))
temp.push(xp);
}
else if(spl[q].startsWith("OU") || spl[q].startsWith("DC"))
{
temp.push(spl[q].split(",")[0]);
}
}
console.log("TEMP : "+temp);
/*for(q=0;q<cnt;q++)
{
var test=0;
for(m=0;m<temp.length;m++)
{
var textData=spl[q]+"";
console.log(temp[m]);
if(textData.Contains(temp[m]))
test=1;
}
if(test==0)
{
if (spl[q].startsWith(","))
arrayCollection.push(spl[q].split(",")[1]);
else
arrayCollection.push(spl[q].split(",")[0]);
}
}*/
for (q = 0; q < cnt; q++) {
if (spl[q].startsWith(","))
dt=/*spl[q].split(",")[1]//*/dt ={"id":spl[q].split(",")[1],"text":spl[q].split(",")[1]}
else
dt=/*spl[q].split(",")[0]//*/dt = {"id": spl[q].split(",")[0] ,"text": spl[q].split(",")[0] };
arrayCollection.push(dt);
}
refreshJSTree();
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="jstree.min.js"></script>
<button onclick="callGraph()">>></button>
<button onclick="deleteNode()"><<</button>
<script>
$('#html').jstree();
$('#frmt').jstree({
'core': {
'data':<%= session.getAttribute("PATH")%>
},
"checkbox": {
"whole_node": false,
"keep_selected_style": true,
"three_state": true,
"tie_selection": false
}, "search": {
"fuzzy": true
}, "plugins": ["checkbox", "search"]
});
$('#frmt1').jstree({
'core': {
'data':[{"text":"DC TEST"}]
},
"checkbox": {
"whole_node": false,
"keep_selected_style": true,
"three_state": true,
"tie_selection": false
}, "search": {
"fuzzy": true
}, "plugins": ["checkbox", "search"]
});
/*$('button').on('click', function () {
a = $('#frmt').jstree("get_checked");
callGraph(a);
// window.location = "read.jsp?name="+a;
});*/
</script>
</body>
</html>

Categories

Resources