Independent HTTP status for each array element - javascript

I am using the following code to print some information in HTML.
I have problems.
First, I use:
fetch(resultado.url).then(function(response) {console.log(response.status);
To obtain the http status of the URL that is inside the array "channelList", but I don't know how to get that state independently, I mean, for all elements of the array.
And after that, if I change 'getElementbyID' to 'getElementbyClassName' to show 'status' in HTML, this doesn't work
const channelList = [
{
name: "La 1",
title: "RTVE La 1",
link: "go:la1",
imgClass: "la1",
flag: "es",
url: "./la1.html",
},
{
name: "La 2",
title: "RTVE La 2",
link: "go:la1",
imgClass: "la1",
flag: "es",
url: "./la2.html",
},
];
const resultado = channelList.find( canal => canal.name === 'La 1' );
// HTTP STATUS
fetch(resultado.url).then(function(response) {
console.log(response.status);
if(response.status !== 200){
let stt = document.getElementById('hlstatus');
stt.innerText = "Offline";
} else {
document.getElementById('hlstatus').innerText = "Online";
}
});
// PRINT ON HTML
const container = document.getElementById("locales");
var img = "https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg?v=47faa659a05e";
channelList.forEach(result => {
// Construct card content
const content = `
<div class="col-6 col-sm-4 col-lg-3 col-xl-2">
<div class="dropdown card darkolorbg text-white card-canal card-link text-white">
<a class="card-link text-white" href="${result.link}" ${result.dDown}>
<div class="card-body">
<div class="d-flex justify-content-center">
<img class="canal-img ${result.imgClass}" src="${img}" alt="">
</div>
<div class="d-flex justify-content-center"><h5>${result.name} <span class="hidden">${result.title}</span> <br><span class="subtf1"><i class="flag ${result.flag}"></i></span> <span id="hlstatus"></span> </div>
</div>
</a>
</div>
</div>
`;
// Append newyly created card element to the container
container.innerHTML += content;
});
<div id="locales"></div>

If I understood you correctly, this code should work as you expect.
But pay attention, please, to error processing.
It could be done by passing callback function to .catch method of the promise.
var img = "https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg?v=47faa659a05e";
const container = document.getElementById("locales");
// PRINT ON HTML
function makeStatusCard(result) {
const content = `
<div class="col-6 col-sm-4 col-lg-3 col-xl-2">
${result.status}
<div class="dropdown card darkolorbg text-white card-canal card-link text-white">
<a class="card-link text-white" href="${result.link}" ${result.dDown}>
<div class="card-body">
<div class="d-flex justify-content-center">
<img class="canal-img ${result.imgClass}" src="${img}" alt="">
</div>
<div class="d-flex justify-content-center"><h5>${result.name} <span class="hidden">${result.title}</span> <br><span class="subtf1"><i class="flag ${result.flag}"></i></span> <span id="hlstatus"></span> </div>
</div>
</a>
</div>
</div>
`;
// Append newyly created card element to the container
container.innerHTML += content;
}
const channelList = [
{
name: "La 1",
title: "RTVE La 1",
link: "go:la1",
imgClass: "la1",
flag: "es",
url: "https://avax.dev/data/validators.json",
},
{
name: "La 2",
title: "RTVE La 2",
link: "go:la1",
imgClass: "la1",
flag: "es",
url: "https://avax.dev/data/validators.json",
},
];
// HTTP STATUS
for (let channel of channelList) {
fetch(channel.url).then(function(response) {
channel.status = response.status === 200 ? 'Online' : 'Offline';
makeStatusCard(channel);
});
}
<div id="locales"></div>

Related

Is it a good idea to use images local URL in array?

I want to make a list of projects and I made an array and using .map() method to display them, and I'm adding that list in the HTML element using .insertAdjacentHTML() method.
While inspecting the elements I can see the image path is coming fine but image is not showing in UI. What would be the reason of it?
const projectData = [
{
id: 01,
title: "Project 1",
url: "https://react-projects-1/",
imageUrl: "src/img/projects/project-1.png", //is it wrong using like this
description: "This is project 1 desc",
},
{
id: 02,
title: "Project 2",
url: "https://react-projects-2/",
imageUrl: "src/img/projects/project-2.png", //is it wrong using like this
description: "This is project 2 desc",
},
];
Mapping them and using the HTML:-
const projectHTML = projectData.map((el) => {
return `<div class="row align-items-center project_row">
<div class="col-md-5 col-12 order-md-2">
<a href="${el.url}" class="thumb">
<img
src="${el.imageUrl}"
class="w-100"
alt="${el.title}"
target="_blank"
/>
</a>
</div>
<div class="col-md-7 col-12 order-md-1 mt-4 mt-md-0">
<h3><span>${el.id}.</span>${el.title}</h3>
<p>
${el.description}
</p>
<ul class="buildTech">
<li><i class="fa-brands fa-react"></i> React</li>
</ul>
View
</div>
</div>`;
});
workWrapper.insertAdjacentHTML("afterbegin", projectHTML);
Inspect:-

Handlebars page re-rendering after a query doesn't works

I'm working on a handlebar's page that show some books. Books can be filtered by title or by author or by city/library.
The page is rendered well the first time, but if I use filters and recall the handler with new parameters, the query is executed well (I can see new books' list) but handlebar doesn't update the page with new data
here is a part of my code:
#Get()
#Render("ciclo/index")
async getCicloBooks(
#Query("ciclo") ciclo,
#Query("codProv") codProvincia,
#Query("comune") idComune,
#Query("title") title,
#Query("author") author
) {
let books = undefined;
let comuni = undefined;
let librariesId = [];
const libraries = [];
let data = {};
this.logger.debug("[getCicloBooks] ciclo: " + ciclo);
const province = await this.cicloService.getProvince();
// Titolo
if (title != undefined) {
this.logger.log(`[getCicloBooks] per ciclo: ${ciclo} e titolo ${title}`);
const query = { ciclo: ciclo, title: title };
books = await this.bookService.getBooksByAdvancedQuery(query);
// TODO considerare che lo stesso libro può essere in più librerie
data = {
pageTitle: `Trovate n librerie che hanno in catalogo ${title}`,
ciclo: `${ciclo}`,
books: books,
libraries: null,
provincie: province,
comuni: comuni,
comune: null,
author: `${author}`,
title: `${title}`,
};
} // Autore
else if (author != undefined) {
this.logger.log(`[getCicloBooks] per ciclo: ${ciclo} e autore ${author}`);
const query = { ciclo: ciclo, author: author };
books = await this.bookService.getBooksByCicloAndAuthor(query);
// TODO considerare che lo stesso libro può essere in più librerie
data = {
pageTitle: `Trovate n librerie con libri di ${author}`,
ciclo: `${ciclo}`,
books: books,
libraries: null,
provincie: province,
comuni: comuni,
comune: null,
author: `${author}`,
title: `${title}`,
};
} // Provincia e comune
else if (idComune != undefined) {
this.logger.log(`[getCicloBooks] ciclo: ${ciclo} id comune ${idComune}`);
const comune = await this.cicloService.getComune(idComune);
const allLibraries = await this.cicloService.getAllLibrariesInCities();
this.logger.log("[getCicloBooks] comune " + JSON.stringify(comune));
librariesId = [];
allLibraries.forEach((library) => {
if (library.comune.id == idComune) {
libraries.push(library);
librariesId.push(library.id);
}
});
this.logger.log("[getCicloBooks] ids " + JSON.stringify(librariesId));
const query = { ciclo: ciclo, id: In(librariesId) };
// join book e libreria oppure find in table book_library_libreria where libreriaID in [libreriaId])
books = await this.bookService.getBooksByAdvancedQuery(query);
// this.logger.log("[getCicloBooks] books " + JSON.stringify(books));
books.forEach((book) => {
const libs = [];
book.library.forEach((l) => {
librariesId.forEach((id) => {
if (l.id == id) {
libs.push(l);
}
});
});
book.library = libs;
});
// this.logger.log("[getCicloBooks] books " + JSON.stringify(books));
data = {
pageTitle: `Tutti i libri disponibili per il ciclo: ${ciclo}`,
ciclo: `${ciclo}`,
books: books,
libraries: allLibraries,
provincie: province,
comuni: comuni,
comune: comune,
author: `${author}`,
title: `${title}`,
};
} else {
books = await this.bookService.getBooksByCiclo(ciclo);
data = {
pageTitle: `Tutti i libri disponibili per il ciclo: ${ciclo}`,
ciclo: `${ciclo}`,
books: books,
libraries: null,
provincie: province,
comuni: comuni,
comune: null,
author: `${author}`,
title: `${title}`,
};
}
this.logger.debug("[getCicloBooks] books: " + JSON.stringify(books));
if (books === undefined) {
data = {
title: "Book Store",
subtitle: `Attualmente non abbiamo nessun libro in catalogo per il ciclo ${ciclo}`,
books: null,
province: province,
comuni: comuni,
};
}
// this.logger.log(books);
return { viewData: data };
}
while this is the template code that doesn't update when new data are given
{{#> app}}
{{#*inline "content"}}
<div class="container">
<div class="row" style="margin-top: 25px;">
<div class="col">
<input id="ciclo" name="ciclo" value="{{viewData.ciclo}}" type="hidden">
<h3 class="fw-bold mt-5 text-center">{{ viewData.pageTitle }}</h3>
<h4 class="fw-bold text-center">Raffina la tua ricerca:</h4>
</div>
</div>
<div class="row mt-auto">
<!-- Navigatore delle Tabs -->
<ul class="nav nav-tabs mb-3" id="ex1" role="tablist">
<li class="nav-item" role="presentation">
<a id="tab1" href="#tabPlace" class="nav-link active" data-mdb-toggle="tab" role="tab" aria-controls="tabPlace"
aria-selected="true">Cerca per provincia e comune</a>
</li>
<li class="nav-item" role="presentation">
<a id="tab2" href="#tabAuthor" class="nav-link" data-mdb-toggle="tab" role="tab" aria-controls="tabAuthor"
aria-selected="false">Cerca per autore</a>
</li>
<li class="nav-item" role="presentation">
<a id="tab3" href="#tabTitle" class="nav-link" data-mdb-toggle="tab" role="tab" aria-controls="tabTitle"
aria-selected="false">Cerca per titolo</a>
</li>
</ul>
<!-- Tabs navs -->
</div>
<!-- Tabs content -->
<div id="search-content-tabs" class="tab-content">
<!-- Cerca per comune -->
<div id="tabPlace" class="tab-pane fade show active" role="tabpanel" aria-labelledby="tab-1">
<div class="container">
<div class="row mt-2" style="border: 1px;">
{{!-- blocco provincia --}}
<div class="col-lg-1 col-xs-1" style="margin-top: 8px;"> Provincia:</div>
{{#with viewData}}
<div class="col-lg-3 col-xs-3">
<select name="provincia" id="provinciaDropdown" class="form-select" aria-label="example">
<option value="">Seleziona la Provincia</option>
{{#each provincie}}
<option value="{{codice}}">{{provincia}}</option>
{{/each}}
</select>
</div>
{{/with}}
{{!-- blocco comune --}}
<div class="col-lg-1" style="margin-top: 8px;"> Comune:</div>
<div class="col-lg-3">
<select id="comuneDropdown" name="comune" class="form-select" aria-label="example">
<option value="">Seleziona il Comune</option>
</select>
</div>
</div> <!-- riga dei select provincia e comune -->
<div class="row mt-4"> <!-- riga bottone cerca -->
<div class="col-2">
**<button id="cityBtn" type="submit" class="btn btn-primary" onclick="onCityClicked(event)">Cerca</button>**
</div>
</div>
</div>
</div>
<!-- Cerca per comune -->
<!-- Cerca per autore -->
<div id="tabAuthor" class="tab-pane fade" role="tabpanel" aria-labelledby="tab-2">
<div class="container">
<div class="row mt-2" style="border: 1px;">
{{!-- blocco autore --}}
{{!-- <div class="col-lg-1" style="margin-top: 8px;"> Autore:</div> --}}
<div class="col-lg-3 form-outline">
<input id="formAuthor" type="text" class="form-control form-control-lg" />
<label class="form-label" for="formAuthor">Cerca per autore del libro</label>
</div>
</div>
<div class="row mt-4"> <!-- riga bottone cerca -->
<div class="col-2">
<button id="authorBtn" type="submit" class="btn btn-primary" onclick="onAuthorClicked(event)">Cerca</button>
</div>
</div>
</div>
</div>
<!-- Cerca per autore -->
<!-- Cerca per Titolo -->
<div id="tabTitle" class="tab-pane fade" role="tabpanel" aria-labelledby="tab-3">
<div class="container">
<div class="row mt-2" style="border: 1px;">
<div class="col-lg-1 form-outline">
<input id="formTitle" type="text" class="form-control form-control-lg" />
<label class="form-label" for="formTitle">Cerca per titolo del libro</label>
</div>
</div>
<div class="row mt-4"> <!-- riga bottone cerca -->
<div class="col-2">
<button id="titleBtn" type="submit" class="btn btn-primary" onclick="onTitleClicked(event)">Cerca</button>
</div>
</div>
</div>
</div>
<!-- Cerca per Titolo -->
</div>
<!-- Tabs content -->
</div>
<!-- Blocco Risultato ricerca -->
{{ log viewData}}
<ul id="booksPreview">
{{#each viewData.books}}
<li style="list-style-type: none">
<div class="container mt-5">
<div class="row bt-2" style="margin-top: 20px;">
<div class="col-lg-3 col-md-2 col-lg-2 mb-2">
<img src="/covers/{{getCoverImage}}" style="height: 320px; width: 230px;">
</div>
<div class="col-lg-7 col-md-8 col-lg-6 mb-2">
<div class="text-md-start text-black text-capitalize fa-2x">{{title}}</div>
<div class="text-md-start">Autore {{getAuthor}}</div>
<div class="text-md-start">Prezzo {{getPrice}} €</div>
<div class="text-md-start">Abstract {{getDescription}}</div>
</div>
<div class="col-lg-2 col-md-2 mb-2">
<div class="bi-text-left ">
Aggiungi al carrello
</div>
</div>
</div>
</div>
</li>
{{/each}}
</ul>
<!-- Blocco Risultato ricerca -->
{{/inline}}
{{/app}}
And this is part of scripts's functions called on serch button click
$(document).ready(function () {
$("#provinciaDropdown").on("change", function () {
console.log(`Selected provincia: ${this.value}`);
var country_id = this.value;
$("#comuneDropdown").html("");
uri = `http://${host}:${port}/admin/getComuni?prov=${country_id}`;
$.ajax({
url: uri,
type: "GET",
success: function (result) {
/* console.log(' Result listaComuni ' + result.viewData.comuni); */
if ($.isArray(result.viewData.comuni)) {
$("#comuneDropdown").html(
'<option value="">Seleziona il Comune</option>'
);
comuni = result.viewData.comuni;
for (i = 0; i < comuni.length; i++) {
str = `<option value="${comuni[i].id}"> ${comuni[i].comune} </option>`;
// console.log(str);
$("#comuneDropdown").append(str);
}
} // isArray
}, // success
});
}); // onChange
$("#comuneDropdown").on("change", function () {
var idComune = this.value;
console.log(`Selected comune with id ${this.value}`);
}); // onChange comuneDropdown
});
function onCityClicked(event) {
event.preventDefault();
var city = document.getElementById("comuneDropdown").value;
var ciclo = document.getElementById("ciclo").value;
console.log(`[onCityClicked] ciclo: ${ciclo} city: ${city} `);
var uri = `http://${host}:${port}/ciclo?ciclo=${ciclo}&comune=${city}`;
console.log(`[onCityClicked] uri: ${uri} `);
$.ajax({
url: uri,
type: "GET",
success: function (result) {
data = result.viewData;
console.log("----- SUCCESS -----");
}, // success
}); // ajax
}
So, from main page I show the book's page (default query is executed and template page is rendered successfully), then when I try to change filters, the book's page is called with choosen filters, the query is excuted well (I check logs) but the template doesn't update. I got the previous page
I added to original code the <ul id=".."> <li></li> </ul> tags, trying to intercept at runtime some action on id and clean the book's list before the new render, but I wasn't able to do
Can someone help me?
Thanks

Passing multiple variables into JavaScript function in Template Literals (DOM)

I am looping through an array of objects (rendering data coming from an API) via Vanilla JavaScript (DOM). And I want to pass more than one value (Product ID, Product Name .. etc) to a function triggered in the event of a click button. saveProduct(${proInfo}) as it shown below (proInfo is an object).
The problem is I have been able to pass ONLY ONE value to this function. I tried to pass the variable as an object but it didn't work and got the error (index):1 Uncaught SyntaxError: Unexpected end of input
var shopNcounter = 0;
const baseURL = "***";
const idsArray = [];
const divRow = document.querySelector(".row");
const buttonContainer = document.querySelector("#button-container")
//create column div
function createDiv() {
const div = document.createElement("div");
div.classList.add("col-xl-3");
div.classList.add("col-md-6");
div.classList.add("col-sm-12");
return div;
}
async function getData(id) {
shopNcounter ++;
console.log(shopNcounter);
if(shopNcounter > 5) {
getProInfo(id);
return;
} else if (shopNcounter > 4) {
getProducts(id);
return;
}
idsArray.push(id);
console.log(id);
console.log(idsArray);
if(idsArray.length > 10) {
idsArray.splice(0,6);
}
const api = `**shop=${shopNcounter}&id=${id}`;
try {
const response = await fetch(api);
const data = await response.json();
divRow.innerHTML = "";
if (shopNcounter > 1) {
buttonContainer.innerHTML = `
<button class="btn btn-lg btn-warning px-5" onclick="moveBack(${idsArray[idsArray.length-2]})">رجوع</button>
`
} else {
buttonContainer.innerHTML = "";
}
//mapping through data
data.map(item => {
const div = createDiv();
divRow.appendChild(div);
div.innerHTML+=`
<div class="card text-center h-100 mx-auto border-white shadow" style="width: 16rem;">
<img src="${baseURL + item.image}" class="card-img-top mx-auto" alt="...">
<div class="card-body">
<a onclick=handleClick(${item.id}) class="btn btn-outline-dark px-5 mt-4" id="goToItemButton">${item.name}</a>
</div>
</div>
`;
});
} catch(error) {console.log(error);}
}
getData(0);
async function getProducts(id) {
//shop > 4 = 5
console.log("Get Product is being executing");
const apiProducts = `**product?id=${id}`;
try {
const response = await fetch(apiProducts);
const data = await response.json();
console.log(data);
divRow.innerHTML = "";
//mapping through data
data.map((item, index) => {
var proInfo = {
pid: item.PID,
pname: item.PName
}
const div = createDiv();
divRow.appendChild(div);
div.innerHTML+=`
<div class="card text-center h-100 mx-auto border-white shadow" style="width: 16rem;">
<img src="${baseURL + item.image}" class="card-img-top mx-auto" alt="...">
<div class="card-body">
<h5>${item.PName}</h5>
<p class="product-price">Price: ${item.PSelPrice}</p>
<a onclick=saveProduct(${item.PID}) class="btn btn-danger px-5 mt-4"> Add to Card </a>
</div>
</div>
`;
});
} catch(error) {
console.log(error);
}
}
function moveBack(id) {
shopNcounter = shopNcounter -2;
getData(id);
}
function handleClick(id) {
let clickedButton = document.querySelector("#goToItemButton");
clickedButton.onclick = "";
getData(id);
}
function saveProduct(g) {
console.log(g);
}
your code should not result in the error you see
However you can make your life easier using delegation
do this
document.getElementById("container").innerHTML = data.map((item,i) => `<div class="card text-center h-100 mx-auto border-white shadow" style="width: 16rem;">
<img src="${baseURL + item.image}" class="card-img-top mx-auto" alt="...">
<div class="card-body">
<h5>${item.PName}</h5>
<p class="product-price">Price: ${item.PSelPrice}</p>
<a data-id="${i}" class="add btn btn-danger px-5 mt-4"> Add to Card </a>
</div>
</div>`).join("");
Have this
document.getElementById("container").addEventListener("click",function(e) {
const tgt = e.target.closest("a");
if (tgt && tgt.className.contains("add")) {
const item = data[tgt.dataset.id]
// here you can add the item
saveProduct({pid: item.PID,pname: item.PName })
}
})

JavaScript ajax didn't working.Where am I going wrong?

<div class="media-bottom">
#Html.TextAreaFor(model => model.Message, new { #class = "ui form", #rows = "5", #maxlenght = "300", #placeholder = "Paylaşmak istedikleriniz" })
</div>
<br />
<div class="footer-logo">
<button class=" mini ui right labeled right floated icon button" id="Button_Click" onclick="javascript: Button_Click();">
<i class="right arrow icon"></i>
Paylas
</button>
<div class="container bootstrap snippets bootdey downlines">
<div class="row">
<div class="col-md-6 col-xs-12">
<section class="widget">
<div class="widget-body">
<div class="widget-top-overflow windget-padding-md clearfix bg-info text-white">
</div>
<div class="post-user mt-n-lg">
<span class="thumb-lg pull-left mr media-object">
<img class=" img-circle" src="https://bootdey.com/img/Content/user_3.jpg" alt="...">
</span>
<span class="thumb-lg pull-right mr star">
<img src="~/Content/img/star.png" />
</span>
<div class="Thanksicon">
</div>
<div class="namespace">
<h5 class="mt-sm fw-normal text-black txt post">
#Html.DisplayFor(model => model.FullName)
<br />
<small class="text-black text-light departmen post">#Html.DisplayFor(model => model.Departmen)</small>
</h5>
</div>
</div>
<br />
<br />
<div class="text-light fs-mini m" id="Label1">
<div id="label1">
<p class="article">
#Html.DisplayTextFor(model=>model.Message)
</p>
</div>
<div class="thanksnames">
<span class="thumb-xs avatar mr-sm">
<img class="img-circle thank" src="https://bootdey.com/img/Content/user_2.jpg" alt="...">
</span>
<div class="mt-sm fw-normal text-black " id="person"> <small class="text-black text-light">Rose Tyler</small></div>
</div>
<br />
<div class="img"></div>
<div class="fs-mini text-muted text-right"><time class="time-table-top"></time></div>
</div>
</div>
</section>
</div>
</div>
</div>
This is my javascript
$(function () {
$('#Button_Click').on('click', function () {
$.ajax({
type: "POST",
url: '#Url.Action("Share")',
data: {
fullname: $("#username").val(),
departmen: $("#departmen").val(),
textarea: $(".ui.form").val()
},
datatype: "json",
success: function (data) {
$('.downlines').html(result);
}, error: function (data) {
}
});
});
});
This is my controller httppost
[HttpPost]
private JsonResult Share(SocialMedia data,string id)
{
var employee = _employeeRepository.GetById(id);
ViewBag.IsOwner = id == Session.GetEmployeeNo();
if (Session["MediaList"] == null)
{
Session["MediaList"] = new List<SocialMedia>();
}
var fullname = data.FullName;
var departmen = data.Departmen;
var textarea = data.Message;
foreach (MediaList list in data.MediaLists)
{
list.FullName = fullname;
list.Departmen = departmen;
list.Message = textarea;
list.Date = DateTime.Now.ToLocalTime();
if(data.Photo!=null)
{
list.Photo = data.Photo;
string fileName = Path.GetFileNameWithoutExtension(list.Photo);
list.Photo = "~/Image/" + fileName;
string _path = Path.Combine(Server.MapPath("~/Image/"),fileName);
}
}
return Json(new { data = PartialView("~/Views/SocialMedia/DisplayTemplates/MediaList.cshtml") });
// return PartialView("~/Views/SocialMedia/DisplayTemplates/MediaList.cshtml",
//return Json(new { success = true, message = GlobalViewRes.CreatedSuccessfully }, JsonRequestBehavior.AllowGet);
}
When I write an article and press the button, I want the page to appear below without refreshing and I want it to be repeated. It should be with the whole design. But when I press the button, I made ajax, but my ajax does not work, where am I going wrong?
Sorry for my English:)
success: function (data) {
$('.downlines').html(result);
}, error: function (data) {
}
You handle the data named 'data'. Then you are trying use it like 'result'. What is result, where is it came from? Whatever, try this
$('.downlines').html(data)

Append external json data to div category wise

i dont know how to append external json data to div. i know append with table .but, i am confused with div.please help me to solve this doubt.
because,it need to append data with selected category div.
div1 category [books]
<div class="col-xs-12 col-sm-5 col-md-3 col-lg-2 card">
<!--Card content-->
<div class="card-body">
<!--Title-->
<h4 class="card-title">Card title</h4>
<!--Text-->
<img class="img-fluid z-depth-3 rounded-circle" src="https:/goo.gl/4cPCdn"
alt="Card image cap">
<h4 class="card-title">Category</h4>
<!--Card content-->
Button
</div>
</div>
div 2 category [games]
<div class="col-xs-12 col-sm-5 col-md-3 col-lg-2 card">
<!--Card content-->
<div class="card-body">
<!--Title-->
<h4 class="card-title">Card title</h4>
<!--Text-->
<img class="img-fluid z-depth-3 rounded-circle" src="https:/goo.gl/4cPCdn"
alt="Card image cap">
<h4 class="card-title">Category</h4>
<!--Card content-->
Button
</div>
</div>
Json
{
"category": {
"books": [
{"title":"Sentra", "url":"https:/goo.gl/4cPCdn","button":"https:google.in"},
{"title":"Maxima", "url":"https:/goo.gl/4cPCdn"},"button":"https:google.in"}
],
"games": [
{"title":"Taurus", "url":https:/goo.gl/4cPCdn},"button":"https:/google.in"}
{"title":"Escort", "url":https:/goo.gl/4cPCdn},"button":"https:/google.in"}
]
}
}
Javascript & jquery
<script>
$.ajax({
url: 'json-data.json',
type: "get",
dataType: "json",
success: function (data) {
drawTable(data);
}
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
**This part i dont know please teach me**
}
</script>
Fiddle
Fiddle codes click to edit
This isn't perfect but it should give you some help in understanding how to append to a div via jQuery. Your data was messed up, so I fixed it and made it a valid object. You may want to use things like JSLint to check your data before testing your pages - https://jsonlint.com/
var data = {
"category": {
"books": [
{"title":"Sentra", "url":"https:/goo.gl/4cPCdn", "button":"https:google.in"},
{"title":"Maxima", "url":"https:/goo.gl/4cPCdn", "button":"https:google.in"}
],
"games": [
{"title":"Taurus", "url":"https:/goo.gl/4cPCdn","button":"https:/google.in"},
{"title":"Escort", "url":"https:/goo.gl/4cPCdn","button":"https:/google.in"}
]
}
}
/* not needed for test, we've already included our data above
$.ajax({
url: 'json-data.json',
type: "get",
dataType: "json",
success: function (data) {
drawTable(data);
}
});
*/
data = data.category;
drawTable(data)
function drawTable(theData) {
for (category in theData) {
console.log('category is '+category)
var categoryEntries = theData[category]
for (var i = 0; i < categoryEntries.length; i++) {
var rowData = categoryEntries[i];
drawRow(category,rowData)
}
}
}
function drawRow(category,rowData) {
// console.log(JSON.stringify(rowData))
var title = rowData.title;
var url = rowData.url;
var button = rowData.button
var newDiv = '<div class="card">'+
'<div class="card-body">'+
'<h4 class="card-title">'+title+'</h4>'+
'<img class="img-fluid z-depth-3 rounded-circle" src="'+url+'" alt="Card image cap">'+
'<h4 class="card-title">'+category+'</h4>'+
'Button'+
'</div>'+
'</div>'
$('#'+category).append(newDiv);
}
#books,#games {
display:block;
width: 100%;
clear:both;
}
.card {
float:left;
width: 30vw;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div id="books">
</div>
<div id="games">
</div>

Categories