Showing JSON file into HTML - javascript

Hy everyone. I've been trying to import my JSON to HTML and make it into a table. My JSON contains:
{
"cover_title": "Haikyuu!! TO THE TOP",
"cover_studio": "Production I.G",
"cover_img": "https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx106625-UR22wB2NuNVi.png",
"format": "TV",
"duration": "84%",
"description": "The fourth season of Haikyuu!!\n\nThe Karasuno High School Volleyball Club finally won their way into the nationals after an intense battle for the Miyagi Prefecture Spring Tournament qualifiers. As they were preparing for the nationals, Kageyama is invited to go to All-Japan Youth Training Camp. At the same time, Tsukishima is invited to go to a special rookie select training camp for first-years in Miyagi Prefecture. Hinata feels panic that he\u2019s being left behind as one of the first-years and then decides to show up at the Miyagi Prefecture rookie select training camp anyway...\n\n(Source: Crunchyroll)",
"genres": [
"Comedy ",
" Drama ",
" Sports"
]
},
{
"cover_title": "Eizouken ni wa Te wo Dasu na!",
"cover_studio": "Science SARU",
"cover_img": "https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx109298-YvjfI88hX76T.png",
"format": "TV",
"duration": "79%",
"description": "First year high schooler Midori Asakusa loves anime so much, she insists that \"concept is everything\" in animation. Though she draws a variety of ideas in her sketchbook, she hasn't taken the first step to creating anime, insisting that she can't do it alone. The producer-type Sayaka Kanamori is the first to notice Asakusa's genius. Then, when it becomes clear that their classmate, charismatic fashion model Tsubame Mizusaki, really wants to be an animator, they create an animation club to realize the \"ultimate world\" that exists in their minds.\n\n(Source: Crunchyroll)",
"genres": [
"Adventure ",
" Comedy"
]
},
and my html is (i got this way from my friend but i dont think this works on my case):
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"> </script>
<script>
$(function(){
$.get('anime.json', function(obj){
var str = "";
str+="<table border = '1'><tr><th>No</th><th>Judul</th></tr>";
$.each(obj, function(n,data){
str+="<tr><td>"+(n+1)+"</td>";
str+= "<td>"+data.cover_title+"</td></tr>";
});
$('#media').html(str);
});
});
</script>
</head>
<body>
<div id = "media"></div>
</body>
</html>
I've also try another ways from youtube, but it's still not working. What can I do? Thankyou.

jQuery Get function tries to automatically parse the json string and convert it to an array but when it encounters an internal error the success callback won't run.
Your json format doesn't look valid, you can confirm using this
$.get('a.json', function(obj){
var str = "";
str+="<table border = '1'><tr><th>No</th><th>Judul</th></tr>";
$.each(obj, function(n,data){
str+="<tr><td>"+(n+1)+"</td>";
str+= "<td>"+data.cover_title+"</td></tr>";
});
$('#media').html(str);
})
.catch( function(e){
alert('Error');
});
Your should correct it like
[{
"cover_title": "Haikyuu!! TO THE TOP",
"cover_studio": "Production I.G",
"cover_img": "https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx106625-UR22wB2NuNVi.png",
"format": "TV",
"duration": "84%",
"description": "The fourth season of Haikyuu!!\n\nThe Karasuno High School Volleyball Club finally won their way into the nationals after an intense battle for the Miyagi Prefecture Spring Tournament qualifiers. As they were preparing for the nationals, Kageyama is invited to go to All-Japan Youth Training Camp. At the same time, Tsukishima is invited to go to a special rookie select training camp for first-years in Miyagi Prefecture. Hinata feels panic that he\u2019s being left behind as one of the first-years and then decides to show up at the Miyagi Prefecture rookie select training camp anyway...\n\n(Source: Crunchyroll)",
"genres": [
"Comedy ",
" Drama ",
" Sports"
]
},
{
"cover_title": "Eizouken ni wa Te wo Dasu na!",
"cover_studio": "Science SARU",
"cover_img": "https://s4.anilist.co/file/anilistcdn/media/anime/cover/large/bx109298-YvjfI88hX76T.png",
"format": "TV",
"duration": "79%",
"description": "First year high schooler Midori Asakusa loves anime so much, she insists that \"concept is everything\" in animation. Though she draws a variety of ideas in her sketchbook, she hasn't taken the first step to creating anime, insisting that she can't do it alone. The producer-type Sayaka Kanamori is the first to notice Asakusa's genius. Then, when it becomes clear that their classmate, charismatic fashion model Tsubame Mizusaki, really wants to be an animator, they create an animation club to realize the \"ultimate world\" that exists in their minds.\n\n(Source: Crunchyroll)",
"genres": [
"Adventure ",
" Comedy"
]
}]

Related

JSON select data at specific ID

In PHP, I've created a function to create a JSON file:
function writeJSONData(PDO $conn): void
{
$contentJSON = "SELECT * FROM tb_content";
$contentResultsJSON = $conn->query($contentJSON);
$contentJSONExt = array();
while ($JSON = $contentResultsJSON->fetchAll(PDO::FETCH_ASSOC)) {
$contentJSONExt = $JSON;
}
$infoJSON[] = json_encode(array('movies' => $contentJSONExt));
$target_dir = $_SERVER['DOCUMENT_ROOT'] . "/CineFlex/private/api/api.json";
file_put_contents($target_dir, $infoJSON);
}
In my HTML file I've created a button which sends the ID of the selected movie:
<!-- Edit Button -->
<button onclick="toggleDialog(editMovie, this.id)" id="<?php echo($info['content_id']) ?>Edit Movie</button>
My JavaScript file contains the function:
// Toggle Dialog
function toggleDialog(dialogName, dialogID) {
// Toggle Dialog Visibility
$(dialogName).fadeToggle(200);
$.getJSON("./private/api/api.json", function (data) {
console.log(data)
})
}
When I click on the edit button, it prints the entire JSON file in the console. Which is understandable.
Current output:
{
"movies": [
{
"content_id": 15,
"title": "Scream (2022)",
"description": "25 years after a streak of brutal murders shocked the quiet town of Woodsboro, Calif., a new killer dons the Ghostface mask and begins targeting a group of teenagers to resurrect secrets from the town's deadly past."
},
{
"content_id": 16,
"title": "Fear Street: Part Two - 1978",
"description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
},
{
"content_id": 17,
"title": "Archive 81",
"description": "An archivist hired to restore a collection of tapes finds himself reconstructing the work of a filmmaker and her investigation into a dangerous cult."
}
]
}
Now my issue is, I want the "dialogID" to be selected from the JSON file where it matches with "content_id". For example: When I click on a movie with 16 as "dialogID", I want the console to just print everything from that array.
Expected output:
{
"movies": [
{
"content_id": 16,
"title": "Fear Street: Part Two - 1978",
"description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
}
]
}
To get it, you need to create dynamic API instead of static file content. In alternative case, you can get it only from JS loop (check all and check suitable ID). If you want to do it with API, you must change html and php script like this:
function getDataById(PDO $conn):string
{
$id = (int) $_GET['id'];
$contentJSON = "SELECT * FROM tb_content where id = :id";
$contentResultsJSON = $conn->prepare($contentJSON);
$contentResultsJSON->execute([':name' => 'David', ':id' => $_SESSION['id']]);
$rows = $contentResultsJSON->fetchAll(PDO::FETCH_ASSOC);
$contentJSONExt = array();
while ($JSON =$rows) {
$contentJSONExt = $JSON;
}
return json_encode(array('movies' => $contentJSONExt));
}
And, JS codes to change like this:
// Toggle Dialog
function toggleDialog(dialogName, dialogID) {
// Toggle Dialog Visibility
$(dialogName).fadeToggle(200);
$.getJSON("https://my-site.com/getDataById/?id="+dialogID, function (data) {
console.log(data)
})
}
I don't know if you want to select in your php the right ID, and send back only the right one or if you want the whole json back and select in javascript.
First answer here gives the answer to dynamic php: only the right ID back from server.
I will try to answer the second possibility: all json movies back, selection in javascript.
html (3 buttons for example):
<button onclick="toggleDialog(this.id)" id="15">Edit Movie 15</button>
<button onclick="toggleDialog(this.id)" id="16">Edit Movie 16</button>
<button onclick="toggleDialog(this.id)" id="17">Edit Movie 17</button>
javascript, let say we have back the whole json movies, I put a variable here (it's supposed to be the whole json back from php):
let json = {
"movies": [
{
"content_id": 15,
"title": "Scream (2022)",
"description": "25 years after a streak of brutal murders shocked the quiet town of Woodsboro, Calif., a new killer dons the Ghostface mask and begins targeting a group of teenagers to resurrect secrets from the town's deadly past."
},
{
"content_id": 16,
"title": "Fear Street: Part Two - 1978",
"description": "Shadyside, 1978. School's out for summer and the activities at Camp Nightwing are about to begin. But when another Shadysider is possessed with the urge to kill, the fun in the sun becomes a gruesome fight for survival."
},
{
"content_id": 17,
"title": "Archive 81",
"description": "An archivist hired to restore a collection of tapes finds himself reconstructing the work of a filmmaker and her investigation into a dangerous cult."
}
]
}
javascript function:
function toggleDialog(dialogID) {
dialogID = parseInt(dialogID);
json.movies.every(e => {
if (e.content_id === parseInt(dialogID)) {
console.log(e.content_id);
console.log(e.title);
console.log(e.description);
return false;
}
return true;
})
}
You iterate through the json.movies (it's an object) with "every" instead of forEach. With every, you can break the loop when condition is met dialogID === content_id with return false. You have to put return true at the end of the loop otherwise it breaks immediately.
Your content_id are numbers, so parseInt on the dialogID. If coming from php json, it'll normally be string so no need for that.
A friend of mine helped me out:
// Toggle Dialog
function toggleDialog(dialogName, dialogID) {
// Toggle Dialog Visibility
$(dialogName).fadeToggle(200);
$.getJSON("./private/api/api.json", function (data) {
for (let i = 0; i < data['movies'].length; i++) {
if (data['movies'][i]['content_id'] == dialogID) {
$('#editMovieTitle').val(data['movies'][i]['title'])
}
}
})
}

How can I remove html data or text when I click button and replace it with data located in a JSON file array using JavaScript

I am attempting a quote generator that when I click the "Generate quote" button it removes the current quote and author and it replaces it with a new quote and author that I have on a JSON file.
The JSON file is in an array. I want it so that every time I click the button the next quote comes up. Ideally I would like it to randomize and provide any of the quotes available within the JSON Array.
Currently I can click the button and the last quote will appear and for every +1 click the same quote appears because the array is picking up the last item and outputting the quote again.
A temporary, but I believe there is a better workaround, is to have multiple JSON files uploaded and changing the page count in the url from '..quotes-'+pagecount+ '.sjon' to get every quote out.
HTML:
<!DOCTYPE html>
<html>
<head>
<!--Javascript for quote generator-->
<link rel="stylesheet" type="text/css" href="css/quoteStyles.css">
</head>
<body>
<div id="quoteBox" class="quote-text">
<span id="text"></span>
<p id="quotePara">
</p>
<span id="text2"></span>
</div>
<div class="quote-author">
- <span id="author"></span>
</div>
<div class="button-links">
<button id="getQuote"class="btn btn-primary">Get Quote</button>
</div>
</body>
<script src="test.js"></script>
<script src="http://rogerperez.us/quotes.json"></script>
Javascript
JavaScript:
var pageCount = 1;
var i=0;
var quotePara = document.getElementById("quotePara");
var getQuote = document.getElementById("getQuote");
// Request to get json data where the quotes are located
getQuote.addEventListener("click", function() {
var ourRequest= new XMLHttpRequest();
ourRequest.open('GET','http://rogerperez.us/quotes-1.json');
ourRequest.onload= function() {
if (ourRequest.status>= 200 && ourRequest.status<400){
var ourData= JSON.parse(ourRequest.responseText);
renderHTML(ourData);
} else{
console.log("Connection Error, Please try again.")
}
};
ourRequest.send();
pageCount++;
if (pageCount>6){
getQuote.classList.add('hide-me');
}
});
console.log(i);
function renderHTML(data){
var htmlString="";
var htmlAuthor="";
// for (j=0;j<data.length;j++){
// remove
// }
for (i=0;i<data.length; i++){
console.log("first",i);
htmlString=data[i].quote;
htmlAuthor=data[i].author;
console.log(i);
}
quotePara.insertAdjacentHTML('beforeend', htmlString);
author.insertAdjacentHTML('beforeend', htmlAuthor);
}
Json
[
{"quote": "Success is not final; failure is not fatal: It is the courage to
continue that counts.",
"author": "Winston S. Churchill"},
{"quote":"Don't be afraid to give up the good to go for the great.",
"author":"John D. Rockefeller"},
{"quote":"I find that the harder I work, the more luck I seem to have.",
"author":"Thomas Jefferson"},
{"quote":"Try not to become a man of success. Rather become a man of value.",
"author":"Albert Einstein"},
{"quote":"o one thing every day that scares you.",
"author":"Anonymous"},
{"quote":"If you really look closely, most overnight successes took a long
time.",
"author":"Steve Jobs"},
{"quote":"The real test is not whether you avoid this failure, because you won't. It's whether you let it harden or shame you into inaction, or whether you learn from it; whether you choose to persevere.",
"author":"Barack Obama"},
{"quote":"The successful warrior is the average man, with laser-like focus.",
"author":"Bruce Lee"},
{"quote":"If you really want to do something, you'll find a way. If you don't, you'll find an excuse.",
"author":"Jim Rohn"},
{"quote":"Be the type of person that when your feet hit the floor in the
morning the devil says,aww shit.. they are up",
"author":"Dwayne (The Rock) Johnson"},
{"quote":"Many of life's failures are people who did not realize how close
they were to success when they gave up",
"author":"Thomas Edison"},
{"quote":"Opportunities don't happen. You create them",
"author":"Chris Grosser"},
{"quote":"I would rather risk wearing out than rusting out.",
"author":"Theodore Roosevelt"},
{"quote":"When you play, play hard; when you work, don't play at all.",
"author":"Theodore Roosevelt"}
]
Your trouble is that you're iterating through the whole data array, replacing your variable values, and then only retaining the value of the very last data value:
// your code
for (i=0;i<data.length; i++){
console.log("first",i);
htmlString=data[i].quote;
htmlAuthor=data[i].author;
console.log(i);
}
quotePara.insertAdjacentHTML('beforeend', htmlString);
author.insertAdjacentHTML('beforeend', htmlAuthor);
If you wanted to, for instance, make the pageCount array index quote show, you would just do:
// I recommend textContent instead
quotePara.textContent = data[pageCount].quote;
author.textContent = data[pageCount].author;
Not completely sure what the objective is here. But here is my 5 cents worth.
The json can be just added to the code - If this is preset as per your example then just load it with the HTML. It would be smarter to append it server side and simpler. If you want to make it an ajax http request do it once at the start of your code when the button is clicked, cache it in a varible and next time the button is clicked before you do your ajax request check if the varible already has it.
Your var i being the current Quote index needs to be incremented on the button click see my code - if this is to be random, comment and I will adjust.
I have simplified the rendering. If you want some fancy rendering, ie you want to render all of the quotes as they are requested again comment and I will adjust
Here is a fiddle
https://jsfiddle.net/p13c8L2w/2/
var QUOTES = [{
"quote": "Success is not final; failure is not fatal: It is the courage to continue that counts.",
"author": "Winston S. Churchill"
}, {
"quote": "Don't be afraid to give up the good to go for the great.",
"author": "John D. Rockefeller"
}, {
"quote": "I find that the harder I work, the more luck I seem to have.",
"author": "Thomas Jefferson"
}, {
"quote": "Try not to become a man of success. Rather become a man of value.",
"author": "Albert Einstein"
}, {
"quote": "o one thing every day that scares you.",
"author": "Anonymous"
}, {
"quote": "If you really look closely, most overnight successes took a long time.",
"author": "Steve Jobs"
}, {
"quote": "The real test is not whether you avoid this failure, because you won't. It's whether you let it harden or shame you into inaction, or whether you learn from it; whether you choose to persevere.",
"author": "Barack Obama"
}, {
"quote": "The successful warrior is the average man, with laser-like focus.",
"author": "Bruce Lee"
}, {
"quote": "If you really want to do something, you'll find a way. If you don't, you'll find an excuse.",
"author": "Jim Rohn"
}, {
"quote": "Be the type of person that when your feet hit the floor in the morning the devil says,aww shit.. they are up",
"author": "Dwayne (The Rock) Johnson"
}, {
"quote": "Many of life's failures are people who did not realize how close they were to success when they gave up",
"author": "Thomas Edison"
}, {
"quote": "Opportunities don't happen. You create them",
"author": "Chris Grosser"
}, {
"quote": "I would rather risk wearing out than rusting out.",
"author": "Theodore Roosevelt"
}, {
"quote": "When you play, play hard; when you work, don't play at all.",
"author": "Theodore Roosevelt"
}];
var i = 0;
var quotePara = document.getElementById("quotePara");
var getQuote = document.getElementById("getQuote");
// Request to get json data where the quotes are located
getQuote.addEventListener("click", function() {
renderHTML(QUOTES);
// if the current index is the end restart back at 0
if (i===QUOTES.length) i=0;
});
function renderHTML(data) {
var htmlString = "";
var htmlAuthor = "";
htmlString = data[i].quote;
htmlAuthor = data[i].author;
// i'm just fetching the next quote, for a random quote I would just use
// some random number logic from 0-length of quotes,
i++;
// I'm just building some html to show the quote
quotePara.innerHTML= ["<h2>", htmlString, "</h2>", htmlAuthor].join("");
}
I create simple loop with call function renderHTML
Here is my fiddle:
jsfiddle
var QUOTES = [{
"quote": "Success is not final; failure is not fatal: It is the courage to continue that counts.",
"author": "Winston S. Churchill"
}, {
"quote": "Don't be afraid to give up the good to go for the great.",
"author": "John D. Rockefeller"
}, {
"quote": "I find that the harder I work, the more luck I seem to have.",
"author": "Thomas Jefferson"
}, {
"quote": "Try not to become a man of success. Rather become a man of value.",
"author": "Albert Einstein"
}, {
"quote": "o one thing every day that scares you.",
"author": "Anonymous"
}, {
"quote": "If you really look closely, most overnight successes took a long time.",
"author": "Steve Jobs"
}, {
"quote": "The real test is not whether you avoid this failure, because you won't. It's whether you let it harden or shame you into inaction, or whether you learn from it; whether you choose to persevere.",
"author": "Barack Obama"
}, {
"quote": "The successful warrior is the average man, with laser-like focus.",
"author": "Bruce Lee"
}, {
"quote": "If you really want to do something, you'll find a way. If you don't, you'll find an excuse.",
"author": "Jim Rohn"
}, {
"quote": "Be the type of person that when your feet hit the floor in the morning the devil says,aww shit.. they are up",
"author": "Dwayne (The Rock) Johnson"
}, {
"quote": "Many of life's failures are people who did not realize how close they were to success when they gave up",
"author": "Thomas Edison"
}, {
"quote": "Opportunities don't happen. You create them",
"author": "Chris Grosser"
}, {
"quote": "I would rather risk wearing out than rusting out.",
"author": "Theodore Roosevelt"
}, {
"quote": "When you play, play hard; when you work, don't play at all.",
"author": "Theodore Roosevelt"
}];
var pageCount = -1;
var getQuote = document.getElementById("getQuote");
// Request to get json data where the quotes are located
getQuote.addEventListener("click", function() {
if (pageCount===QUOTES.length) pageCount=-1;
pageCount++;
renderHTML(pageCount,QUOTES);
});
function renderHTML(i,data) {
var htmlString = "";
var htmlAuthor = "";
htmlString = data[i].quote;
htmlAuthor = data[i].author;
document.getElementById("quote").innerText = htmlString;
document.getElementById("author").innerText = htmlAuthor;
document.getElementById("page-num").innerText = i;
}
<div>
<span id="quote"></span>
</div>
<div>
<span id="author"></span>
</div>
<div>
<span id="page-num"></span>
</div>
<div>
<button id="getQuote"class="btn btn-primary">Get Quote</button>
</div>
if you dont need loop, simply you can call function renderHTML when pageCount!=QUOTES.length

How do I maintain the same JSON format from web API response after an AJAX call?

I have a web API that returns the following JSON:
[{"MovieId":2,"Title":"End Game","Year":"2013","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick Fabian","Plot":"A secret Service agent and a news reporter investigate the conspiracy behind the assassination of the President","Director":"Andy Cheng","Cover":"Endgame-movie-cover.jpg"},{"MovieId":3,"Title":"Saving Private Ryan","Year":"1998","Actors":"Tom Hanks, Tom Sizemore, Edward Burns, Barry Pepper","Plot":"Following the Normandy Landings, a group of U.S. soldiers go behind enemy lines to retrieve a paratrooper whose brothers have been killed in action","Director":"Steven Spielberg","Cover":"Saving-Private-Ryan-Cover.jpg"}]
I want to pass JSON from the response to jqGrid to populate the data in a table, after my AJAX call which looks as follows:
function fetchMovies(){
$.ajax({
url: 'http://orionadmin.azurewebsites.net/api/movies',
type: 'GET',
datatype: 'JSON',
contentType: 'application/json',
success: function (data) {
grid_data1 = JSON.stringify(data);
alert(grid_data);
},
error: function (x, h, r) {
alert('Something went wrong')
}
});
}
My result from the AJAX call looks as follows:
"[{"MovieId":2,"Title":"End Game","Year":"2013","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick Fabian","Plot":"A secret Service agent and a news reporter investigate the conspiracy behind the assassination of the President","Director":"Andy Cheng","Cover":"Endgame-movie-cover.jpg"},{"MovieId":3,"Title":"Saving Private Ryan","Year":"1998","Actors":"Tom Hanks, Tom Sizemore, Edward Burns, Barry Pepper","Plot":"Following the Normandy Landings, a group of U.S. soldiers go behind enemy lines to retrieve a paratrooper whose brothers have been killed in action","Director":"Steven Spielberg","Cover":"Saving-Private-Ryan-Cover.jpg"}]"
This is the format jqGrid takes, to populate data in the table:
<script type="text/javascript">
var grid_data =
[
{id:"1",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx", sdate:"2007-12-03"},
{id:"2",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime",sdate:"2007-12-03"},
{id:"3",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
{id:"4",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX",sdate:"2007-12-03"},
{id:"5",name:"Laser Printer",note:"note2",stock:"Yes",ship:"FedEx",sdate:"2007-12-03"},
{id:"6",name:"Play Station",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
{id:"7",name:"Mobile Telephone",note:"note",stock:"Yes",ship:"ARAMEX",sdate:"2007-12-03"},
{id:"8",name:"Server",note:"note2",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
{id:"9",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
{id:"10",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx", sdate:"2007-12-03"},
{id:"11",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime",sdate:"2007-12-03"},
{id:"12",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
{id:"13",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX",sdate:"2007-12-03"},
{id:"14",name:"Laser Printer",note:"note2",stock:"Yes",ship:"FedEx",sdate:"2007-12-03"},
{id:"15",name:"Play Station",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
{id:"16",name:"Mobile Telephone",note:"note",stock:"Yes",ship:"ARAMEX",sdate:"2007-12-03"},
{id:"17",name:"Server",note:"note2",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
{id:"18",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
{id:"19",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
{id:"20",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx", sdate:"2007-12-03"},
{id:"21",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime",sdate:"2007-12-03"},
{id:"22",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
{id:"23",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX",sdate:"2007-12-03"}
];
How do I maintain the original JSON format without the " " after the AJAX call, so that I can get my data displayed in my jqGrid?
Maybe something like this?
'[{"MovieId":2,"Title":"End Game","Year"...'.replace(new RegExp('"', 'g'), '')
You don't need JSON.stringify(), your data is already in json format
JSON is basically a format where you pass Javascript as a string. JQuery actually parses the string into an object, which is what you want. But you are then transforming the object into JSON again, which is a string, but what you really want to use is the object.
TL;DR: Don't stringify it
You can use addRowData method of JqGrid. it expects an object as input, since your result is an array of objects you just need to loop through the array and add Row Data
var data = [{"MovieId":2,"Title":"End Game","Year":"20113","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick Fabian","Plot":"A secret Service agent and a news reporter investigate the conspiracy behind the assassination of the President","Director":"Andy Cheng","Cover":"Endgame-movie-cover.jpg"},{"MovieId":3,"Title":"Saving Private Ryan","Year":"1998","Actors":"Tom Hanks, Tom Sizemore, Edward Burns, Barry Pepper","Plot":"Following the Normandy Landings, a group of U.S. soldiers go behind enemy lines to retrieve a paratrooper whose brothers have been killed in action","Director":"Steven Spielberg","Cover":"Saving-Private-Ryan-Cover.jpg"},{"MovieId":4,"Title":"Cobra","Year":"1986","Actors":"Sylvester Stallone, Brigitte Nielsen, Reni Santoni, Andrew Robinson","Plot":"A tough-on-crime street cop must protect the only surviving witness to a strange murderous cult with far reaching plans","Director":"George P. Cosmatos","Cover":"cobra.jpg"},{"MovieId":5,"Title":"Savages","Year":"2012","Actors":"Blake Lively, Taylor Kitsch, Aaron Taylor-Johnson, Jana Banker","Plot":"Pot growers Ben and Chon face off against the Mexican drug cartel who kidnapped their shared girlfriend","Director":"Oliver Stone","Cover":"savages.jpg"},{"MovieId":6,"Title":"The Man in the Iron Mask","Year":"1998","Actors":"Leonardo DiCaprio, Jeremy Irons, John Malkovich, GĂ©rard Depardieu","Plot":"The cruel King Louis XIV of France has a secret twin brother who he keeps imprisoned. Can the twin be substituted for the real king?\"","Director":"Randall Wallac","Cover":"maninimask.jpg"},{"MovieId":7,"Title":"The Shawshank Redemption","Year":"1994","Actors":"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler","Plot":"Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.","Director":"Frank Darabont","Cover":"MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_SX300.jpg"},{"MovieId":8,"Title":"Perfume: The Story of a Murderer","Year":"2006","Actors":"Ben Whishaw, Francesc Albiol, Gonzalo Cunill, Roger Salvany","Plot":"Jean-Baptiste Grenouille, born with a superior olfactory sense, creates the world's finest perfume. His work, however, takes a dark turn as he searches for the ultimate scent.","Director":"Tom Tykwer","Cover":"MV5BMTI0NjUyMTk3Nl5BMl5BanBnXkFtZTcwOTA5MzkzMQ##._V1_SX300.jpg"},{"MovieId":9,"Title":"Catch Me If You Can","Year":"2002","Actors":"Leonardo DiCaprio, Tom Hanks, Christopher Walken, Martin Sheen","Plot":"The true story of Frank Abagnale Jr. who, before his 19th birthday, successfully conned millions of dollars' worth of checks as a Pan Am pilot, doctor, and legal prosecutor.","Director":"Steven Spielberg","Cover":"MV5BMTY5MzYzNjc5NV5BMl5BanBnXkFtZTYwNTUyNTc2._V1_SX300.jpg"},{"MovieId":10,"Title":"James Bond 007","Year":"2003","Actors":"Pierce Brosnan, John Cleese, Willem Dafoe, Judi Dench","Plot":"MI6 agent James Bond:007 rushes into action to rescue Oxford scientist Katya Nadanova from a terrorist facility in Egypt. After rescuing Katya bond heads to a mining town in Peru to ..","Director":"Scot Bayless","Cover":"007.jpg"},{"MovieId":11,"Title":"The Mask","Year":"1994","Actors":"Jim Carrey, Peter Riegert, Peter Greene, Amy Yasbeck","Plot":"Bank clerk Stanley Ipkiss is transformed into a manic superhero when he wears a mysterious mas","Director":"Chuck Russel","Cover":"theMask.jpg"},{"MovieId":12,"Title":"Rambo","Year":"2008","Actors":"Sylvester Stallone, Julie Benz, Matthew Marsden, Graham McTavish","Plot":"In Thailand, John Rambo joins a group of missionaries to venture into war-torn Burma, and rescue a group of Christian aid workers who were kidnapped by the ruthless local infantry unit","Director":"Sylvester Stallone","Cover":"rambo.jpg"},{"MovieId":13,"Title":"The Green Mile","Year":"1999","Actors":"Tom Hanks, David Morse, Michael Clarke Duncan, Bonnie Hunt\",\"Plot\":\"The lives of guards on Death Row are affected by one of their charges: a black man accused of child murder and rape, yet who has a mysterious gift","Plot":"The lives of guards on Death Row are affected by one of their charges: a black man accused of child murder and rape, yet who has a mysterious gift.\",\"Language\":\"English, French\",\"Country\":\"USA\",\"Awards\":\"Nominated for 4 Oscars. Another 15 wins & 30 nominations","Director":"Frank Darabont","Cover":"greenmile.jpg"}]
$("#grid").jqGrid({
datatype: "local",
height: 250,
colNames: ['MovieId', 'Title', 'Title', 'Actors', 'Plot','Director'],
colModel: [{
name: 'MovieId',
index: 'MovieId',
width: 60,
search:false},
{
name: 'Title',
index: 'Title',
width: 120,
search:false},
{
name: 'Year',
index: 'Year',
width: 60,
search:false},
{
name: 'Actors',
index: 'Actors',
width: 120,
search:false},
{
name: 'Plot',
index: 'Plot',
width: 120,
search:false},
{
name: 'Director',
index: 'Director',
width: 120,
search:false}
],
caption: "IMDB"
});
for (var i = 0; i <= data.length; i++) {
$("#grid").jqGrid('addRowData', i + 1, data[i]);
}
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/free-jqgrid/4.13.5/css/ui.jqgrid.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/free-jqgrid/4.13.5/js/jquery.jqgrid.min.js"></script>
<table id="grid"></table>

Display break tags in Jade Mixin

I have a JSON file that is being called inside of a Jade Mixin to display text. However, I need to insert a break tag in one of the JSON fields and don't know how to accomplish this inside the Jade Mixin. I can't seem to find the relevant information anywhere.
Here's the JSON file:
"features": {
"employers": {
"title": "For Employers",
"description": "Company corporate financial wellness program is designed to help employers lessen financial stress in the workplace, increase retirement readiness, and strengthen workplace culture.<br />Company offers a holistic approach to corporate financial wellness.",
"featureList": [
{
"iconSlug": "puzzle",
"title": "Easy Implementation",
"description": "Company provides a robust, custom marketing and communication plan to help drive program awareness and engagement."
},
{
"iconSlug": "rays",
"title": "Ongoing Engagement",
"description": "Get metrics around your employees’ engagement with the program and workplace impact."
},
{
"iconSlug": "dollarSign",
"title": "Affordable Pricing",
"description": "Explore our pricing options for all company sizes, including low, per- employee rates that can be paid out of ERISA budgets."
}
],
"cta": {
"title": "Contact our team",
"class": "trigger-emailFormScroll"
}
}
And Here is the Mixin that pulls it in:
mixin FeaturesModule(config)
h3.lvHeading.lvHeading-size3.lvHeading-main= config.title
h5.lvHeading.lvHeading-size5= config.description
- if (config.cta && typeof config.cta.newPage === "undefined") { config.cta.newPage = true; }
.layout-stdGrid
each feature, i in config.featureList
.stdGrid-col8.stdGrid-col-thin.padding-2
abbr(class= "icon-mktgLight-" + feature.iconSlug)
h6.lvHeading.lvHeading-size5.lvHeading-main!= feature.title
span.block= feature.description
- if (config.featuredLink)
a.link-featured.margin-Y-1.block(href= config.featuredLink.href, name=config.featuredLink.title, target= "_blank")= config.featuredLink.title
- else if (config.cta)
- if (config.cta.href)
a.button.button-wide(href= config.cta.href, target= (config.cta.newPage) ? "_blank" : undefined)= config.cta.title
- else
- var ctaClass = config.cta.class || "";
button.button.button-wide(class= ctaClass)= config.cta.title
The span.block = feature.description is what I'm working with at the moment. What is the best way of making the mixin interpret the break tag so it's not printing on the page as text?
Thanks in advance.
Both solution will work:
span.block!=feature.description
span.block!{feature.description}

how do I omit a line when field is empty (using mustache/handlebars)

i'm currently using mustache and trying to implement some basic if-else checking. In my case, I'm checking for a value in a field.
for example:
I have this JSON data:
"AGENCIES":[
{
"IASTATE":"Buenos Aires",
"IAADDRESS1":"Paraguay 647 Piso 4 Of. 17\/18",
"IAADDRESS3":"",
"IALEGALNAME":"Silvia Stocker Australia & New Zealand Travel (ANZ Group)",
"IACOUNTRY":"Argentina",
"IAPRINCIPALAGENT":"",
"IAADDRESS2":"",
"IAAGENCY":"Australia & New Zealand Group (ANZ Group)",
"IAEMAIL":"info#anzgroup.com.ar",
"IAPHONE":"+54 11 4311 9828",
"IAWEBSITE":"http:\/\/www.anzgroup.com.ar\/education-105",
"IACITY":"Buenos Aires",
"IALOCATIONHEAD":"Cecilia Minzio"
},
{
"IAAGENCY":"CW International Education",
"IAADDRESS1":"Juan Francisco Segui 3967",
"IAPRINCIPALAGENT":"",
"IALOCATIONHEAD":"Carola Wober",
"IACOUNTRY":"Argentina",
"IACITY":"Buenos Aires",
"IAPHONE":5.41148010867E11,
"IAADDRESS2":"Piso 6A",
"IAWEBSITE":"http:\/\/www.cwinternationaleducation.com",
"IASTATE":"Buenos Aires",
"IALEGALNAME":"CW International Education",
"IAEMAIL":"info#cwinternationaleducation.com",
"IAADDRESS3":"Ciduad Autonoma"
}]
As you can see from the data above, some fields can be empty like address2 but some data will always have a value like agency name or country or website.
so How can I omit a whole "line" when a field is empty? something like:
<h3>{{IAAGENCY}}<h3>
{{if IAADDRESS2 is not empty}}<span>{{IAADDRESS2}}</span><br />{{/if}}
<span>{{IACOUNTRY}}</span><br />
<span>{{IAWEBSITE}}</span>
Thanks
Using handlebars you can just check the length of the said json-value:
<h3>{{IAAGENCY}}<h3>
{{#if IAADDRESS2.length}}<span>{{IAADDRESS2}}</span><br>{{/if}}
<span>{{IACOUNTRY}}</span><br />
<span>{{IAWEBSITE}}</span>
If the length is 0, it evaluates to false, thus the line is omitted

Categories