Calling REST API with bearer token and fetch url - javascript

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

Related

how to receive inner property string

I want to receive the dependency string from the dataDependencyMap.
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<script>
var data =
[
{
"id": 1,
"active": true,
"dependency": [
{"id": 2, "type": "critical" },
{"id": 3, "type": "moderate"}
]
},
{
"id": 2,
"active": true,
"dependency":[
{"id": 3, "type": "moderate"}
]
},
{
"id": 3,
"active": false,
"dependency":[]
}
]
// this works as it should
var dataActiveMap = new Map(data.map(obj => [obj.id, obj.active]))
data.forEach(function({id}) {
if (dataActiveMap.get(id) == true ) {
console.log(id, "active: ", true)
}
})
// HERE IS THE PROBLEM: How can I return the dependency string, like "critical" or "moderate"
var dataDependencyMap = new Map(data.map(obj => [obj.id, obj.dependency]))
data.forEach(function({id}) {
if (dataActiveMap.get(id) == true) {
console.log(id, "dependency: ", dependency.value)
}
})
</script>
</html>
There is no value property of dependency, you can pass dependency so that you can access that object like the following way:
<script>
var data =
[
{
"id": 1,
"active": true,
"dependency": [
{"id": 2, "type": "critical" },
{"id": 3, "type": "moderate"}
]
},
{
"id": 2,
"active": true,
"dependency":[
{"id": 3, "type": "moderate"}
]
},
{
"id": 3,
"active": false,
"dependency":[]
}
]
// this works as it should
var dataActiveMap = new Map(data.map(obj => [obj.id, obj.active]))
data.forEach(function({id}) {
if (dataActiveMap.get(id) == true ) {
//console.log(id, "active: ", true)
}
})
// HERE IS THE PROBLEM: How can I return the dependency string, like "critical" or "moderate"
var dataDependencyMap = data.map(({id, dependency}) => ({id, dependency}));
data.forEach(function({id, dependency}) {
if (dataActiveMap.get(id) == true) {
//console.log(id, "dependency: ", dependency);
// if you need the *type* property as comma separated string
console.log("id:", id, "and dependency:", dependency.map(({type}) => type).join(', '));
}
})
</script>
I'm not sure what the dataActiveMap constant would be used for but an alternative solution would be to use for loops. If you still need the dataActiveMap and dataDependencyMap, you can always create those arrays and use the push() method to add the values to the arrays at appropriate times in the loops. Check the solution below.
for (key in data){ // loops through the data array
// console.log(data[key])
if (data[key].active) // checks if each object's active property in data array is true
{
// console.log(data[key].dependency)
for (dependency in data[key].dependency) // loops through dependencies
{
// console.log(data[key].dependency[dependency])
for (props in data[key].dependency[dependency]) // loops through objects nested in dependencies
{
console.log(data[key].dependency[dependency].type) //prints the type property
}
}
}
}

How to Gather & Parse JSON Data in HTML

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>

How to concatenate url in React Native

"questionnaire": [
{
"id": 6,
"status": "1",
"name": "Driniking water 24h",
"lang_id": 2,
"zona_id": 7,
"created_at": "2019-05-07 10:35:18",
"updated_at": "2019-06-01 10:01:08",
"questionnaire_category": 1,
"question_number": 1,
"content": "Driniking water Driniking water Driniking water Driniking water"
}
],
"next": {
"id": 7,
"status": "1",
"name": "Public Lighting",
"lang_id": 1,
"zona_id": 7,
"created_at": "2019-05-22 05:04:27",
"updated_at": "2019-06-01 10:00:37",
"questionnaire_category": 1,
"question_number": 2,
"content": "Public Lighting Public Lighting Public Lighting Public Lighting"
}
I have to concatenate the id of questionnaire with id of next, this is my url https://quiet-cove-41253.herokuapp.com/api/questionApi/1 , i don`t know how to concatenate these two id?????
var response = await fetch(`https://quiet-cove-41253.herokuapp.com/api/questionApi/1/6`+this.state.nextData.id);
state = {
data: [],
nextData: []
};
fetchData = async () => {
var response = await fetch(`https://quiet-cove-41253.herokuapp.com/api/questionApi/1/6`+this.state.nextData.id);
var json = await response.json();
this.setState({ data: json.questionnaire, nextData: json.next });
};
componentDidMount() {
this.fetchData();
}
render(){
return(
<View><Text>{this.state.data.id}</Text>
<Text>{this.state.data.name}</Text>
<Text>{this.state.data.content}</Text>
</View>
)
}
My point is that from the next id my questions will change
You can try with
var response = await fetch(`https://quiet-cove-41253.herokuapp.com/api/questionApi/1/6,${this.state.nextData.id}`);

how to insert an array in ajax?

I have modal, inside the modal there is a form when i click the submit button it will do this.
jquery code:
$('#add-new-content-form').on('submit', e => {
e.preventDefault();
//I want to add this block dates to the data
let blockdates = $("#block-dates").val();
let title = $("#card-title").val();
let catalogId = $("#catalog").val();
let categoryId = $("#category").val();
let subcategoryId = $('#subcategory').val();
let why = $("#why").val();
let description = $('#card-description').val();
let cancellationPolicy = $('#cancellation-policy').val();
let displayPrice = $('#display-price').val();
let displayDiscounted = $('#discounted-price').val();
let displayMaxPax = $('#display-maxpax').val();
let data = {
"blockDates":[
{
"description": "national araw ng mga puso day!",
"notAvailableDate": "2019-02-14 10:00:00"
},
{
"description": "chinese new year!",
"notAvailableDate": "2019-02-25 10:00:00"
}
],
"title": title,
"catalogId": catalogId,
"categoryId": categoryId,
"subcategoryId": subcategoryId,
"why": why,
"description": description,
"cancellationPolicy": cancellationPolicy,
"displayPrice": displayPrice,
"displayDiscounted": displayDiscounted,
"displayMaxPax": displayMaxPax
};
let content = ajax("api/unitContents", JSON.stringify(data), "POST");
// window.location.replace("/category");
});
Now, in the postman there is something just like this:
{
"blockDates":[
{
"description": "national araw ng mga puso day!",
"notAvailableDate": "2019-02-14 10:00:00"
},
{
"description": "chinese new year!",
"notAvailableDate": "2019-02-25 10:00:00"
}
],
"location":{
"identifier":"UBZ190asas11",
"name": "abulalas,purok 4",
"address" : "abulalas1 hagonoy bulacan",
"lat" : 12141.00,
"lng" : 123251.00
},
"units": 2,
"title": "sample unit content",
"catalogId": 6,
"categoryId": 22,
"subcategoryId": 13,
"contentOptions": [
{
"name":"bannana boat",
"maxPax":8,
"isAvailableDayTime":[
9,10,11,12,13,15,16,17,18,
33,34,35,36,37,39,38,39,40,
56,57,58,59,60,62,63,64,65,
80,81,82,83,84,86,87,88,89,
104,105,106,107,108,110,111,112,113,
128,129,130,131,132,134,135,136,137,
152,153,154,155,156,158,159,160,161
],
"inventoryNeededSet":[
{
"inventoryId": 1,
"count":1
},
{
"inventoryId": 1,
"count":2
}
],
"paxPrices": [
{
"count": 5,
"pricePerPax": 200,
"totalPrice": 1000,
"fee": 100
},
{
"count": 1,
"pricePerPax": 200,
"totalPrice": 200,
"fee": 10
}
]
},
{
"name":"bannana with island tour",
"maxPax":10,
"isAvailableDayTime":[
9,10,11,12,13,15,16,17,18,
33,34,35,36,37,39,38,39,40,
56,57,58,59,60,62,63,64,65,
80,81,82,83,84,86,87,88,89,
104,105,106,107,108,110,111,112,113,
128,129,130,131,132,134,135,136,137,
152,153,154,155,156,158,159,160,161
],
"inventoryNeededSet":[
{
"inventoryId": 1,
"count":2
},
{
"inventoryId": 1,
"count":2
}
],
"paxPrices": [
{
"count": 5,
"pricePerPax": 200,
"totalPrice": 1000,
"fee": 100
},
{
"count": 1,
"pricePerPax": 200,
"totalPrice": 200,
"fee": 10
}
]
}
],
"photos": [
"https://samplephoto1.com",
"https://samplephoto2.com",
"https://samplephoto3.com"
],
"videos": [
"https://samplevid1.com",
"https://samplevid2.com",
"https://samplevid3.com"
],
"why": "sample why",
"description": "sample desc",
"cancellationPolicy":"cancellationPolicy",
"displayPrice": 300,
"displayDiscounted": 250,
"displayMaxPax": 2
}
the thing is, I want to save the blockdate, what is the syntax of inserting the blockdates?
=======================UPDATED======================
Try this before stringifying the data variable:
data.blockdates = $("#block-dates").val();
To execute your code jQuery is needed. Try after inserting <script src='https://code.jquery.com/jquery-3.3.1.min.js'></script> before your code.
If you have let blockdates = $("#block-dates").val();
You can append blockdates into data like this
data['blockdates']=blockdates;
You may need to keep the elements in an object first. You can then add them to the array.
blockDates= [];
var description = $("#card-description").val();
var notAvailableDate = $("##block-dates").val();
var blockdate = {description, notAvailableDate};
blockDates.push(blockdate);
in this way => let content = ajax("api/unitContents", JSON.stringify(data, blockDates), "POST");
or
let data = {
"title": title,
"catalogId": catalogId,
"categoryId": categoryId,
"subcategoryId": subcategoryId,
"why": why,
"cancellationPolicy": cancellationPolicy,
"displayPrice": displayPrice,
"displayDiscounted": displayDiscounted,
"displayMaxPax": displayMaxPax,
"blockDates": blockDates
};
in this way => `let content = ajax("api/unitContents", JSON.stringify(data), "POST");`

how to create elements dynamically in HTML using JSON file

I want to create HTML elements dynamically using JSON file.
{"myObject": {
"JAVA": {
"id": "JAVAsubj",
"path": "json/data.json"
},
"C#": {
"id": "JAVAsubj",
"path": "json/data1.json"
},
"C++": {
"id": "JAVAsubj",
"path": "json/data2.json"
}
}
}
This is my JSON file. i want to create HTML buttons dynamically. Buttons should be create like JAVA,C#,C++. if i add something next to C++ then that button should get created dynamically
You can try something like this FIDDLE
however, i changed the myObject to an array of json objects as follows:
var jsonObj = {"myObject":
[
{
title: 'JAVA',
id: "JAVAsubj",
path: "json/data.json"
},
{
title: "C#",
id: "JAVAsubj",
path: "json/data1.json"
},
{
title: "C++",
id: "JAVAsubj",
path: "json/data2.json"
}
]
}
var count = Object.keys(jsonObj.myObject).length;
var container= document.getElementById('buttons'); // reference to containing elm
for(var i=0;i<count;i++){
var obj= jsonObj.myObject[i];
var button = "<input type='button' value="+obj.title+"></input>"
container.innerHTML+=button;
}
First thing you need to do that get your JSON into js object :
var myJSON= {"myObject": {
"JAVA": {
"id": "JAVAsubj",
"path": "json/data.json"
},
"C#": {
"id": "JAVAsubj",
"path": "json/data1.json"
},
"C++": {
"id": "JAVAsubj",
"path": "json/data2.json"
}
}
}
now get the value of your object into dictionary like below :
var dctLanguages = myJSON["myObject"];
now to render buttons dynamically, just do this :
var strHTML = '';
for (var key in dctLanguages)
{
var language = dctLanguages[key];
strHTML += '<input type="button" id="'+language.id+'" value="'+key+'"/>';
}
and append this HTML into your container div as follows :
$(strHTML).appendTo("#container");
Hope this will work for you..
const info = [
{
"id": 1,
"img": "a.jpg",
"name": "Avinash Mehta",
"desc": "I am Web Developer"
},
{
"id": 2,
"img": "c.jpg",
"name": "Avinash",
"desc": "I am Web"
},
{
"id": 3,
"img": "b.jpg",
"name": "Mehta",
"desc": "I am Developer"
},
]
const main = document.querySelector(".main");
window.addEventListener("DOMContentLoaded", function(){
let displayInfo = info.map(function(profile){
return` <div class="profile">
<img src="${profile.img}" alt="">
<h2>${profile.name}</h2>
<p>${profile.desc}</p>
</div>`
});
displayInfo = displayInfo.join("");
main.innerHTML = displayInfo
})
This shoule help you
const info = [
{
"id": 1,
"img": "a.jpg",
"name": "Avinash Mehta",
"desc": "I am Web Developer"
},
{
"id": 2,
"img": "c.jpg",
"name": "Avinash",
"desc": "I am Web"
},
{
"id": 3,
"img": "b.jpg",
"name": "Mehta",
"desc": "I am Developer"
},
]
const main = document.querySelector(".main");
window.addEventListener("DOMContentLoaded", function(){
let displayInfo = info.map(function(profile){
return` <div class="profile">
<img src="${profile.img}" alt="">
<h2>${profile.name}</h2>
<p>${profile.desc}</p>
</div>`
});
displayInfo = displayInfo.join("");
main.innerHTML = displayInfo
})

Categories

Resources