Nested JSON to HTML in JavaScript - javascript

I have a json file and I'd like to display it:
Item 1
- Subitem 1.1
- Subitem 1.2
...
Item 2
...
etc.
I have
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$.getJSON("file.json", function(result){
$.each(result.items, function(key, val){
$("#01").append('<p>' + val.item + '</p>');
var id_item;
id_item = '0' + key;
$.each(val.subitems, function(key, val){
$("#02").append('<p><input type="radio" name =' + id_item + ' id =' + key + '>' + val.content + '</input></p>');
});
});
});
});
</script>
Home
<div position="relative" id="01">
<div position="absolute" id="02"></div>
</div>
</body>
</html>
and the result I get is:
Subitem 1.1
Subitem 1.2
...
etc.
Item 1
Item 2
...
etc.
thank you

This snippet shows how you can transform a simple JS object into a HTML representation - does this help?
var items = {
foo: {
bar: 1,
baz: 2,
},
foobar: 3
}
$.each(items, function(key, val){
$("#01").append('<p>' + key + '</p>');
$.each(val, function(key, val){
$("#01").append('<p>- ' + key + ':' + val + '</p>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="01">
</div>

If all you need to do is display print out the data on the page:
var data = [
{key: [1,2,3]}
];
// Clean output, with 4 indentation spaces
var string = JSON.stringify(data, null, ' ');
$('body').append('<pre>' + string + '</pre>');
// Remove brackets
var noBrackets = string.replace(/[,\[\]:{}]/gi, '');
$('body').append('<pre>' + noBrackets + '</pre>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Images in dynamic divs not displayed

I am looping through images and create dynamic divs. But the images are not displayed, though console.log() shows that parameters of ready() function in the loop are valid. It shows myDiv1 and address of the first image in the array and myDiv2 and address of the second image. What's wrong with the code?
Here's my code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="view_topic.css">
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<div id="outerdiv"></div>
<script>
$(document).ready(function() {
$('#outerdiv').append(
$('<div>').prop({
id: 'myDiv1',
//innerHTML: 'Hi there!',
className: 'img-wrapper'
})
);
});
$(document).ready(function() {
$('#outerdiv').append(
$('<div>').prop({
id: 'myDiv2',
//innerHTML: 'Hi there!',
className: 'img-wrapper'
})
);
});
$(this).css('height',"100px");
var get_a_image = ["http://iancaple.ru/upload/images/20200804_225812.jpg", "http://iancaple.ru/upload/images/8871677_tsumpy_laba_3.docx"];
var counter = 1;
var ready_cnt = 0;
for (var i = 0; i < 2; i++) {
$(document).ready(function() {
$('#myDiv' + ready_cnt + 1).append($('<img id="theImg2">').attr({
'src': get_a_image[ready_cnt] , //'https://' + imgUrl ,
'alt': 'test image ' + ready_cnt + 1
})
).scrollTop(9999)
console.log("get_a_image[" + ready_cnt + "]=" + get_a_image[ready_cnt]);
console.log('#myDiv' + (ready_cnt + 1));
ready_cnt++;
});
}
</script>
</body>
<html>
Use parentheses to get the increased value of ready_cnt. If not, it will be regarded to select an ID of myDiv01
$('#myDiv' + (ready_cnt + 1)).append(...)

new line in JS-function

I would like to get a longer string with line breaks, but it's not working with all the common commands like \n, \r\n, ... Also not with HTML-Tags for breaking a line.
I am new to the ASP-Framework and JS-Scripting and I can't find the solution on my own. Till now I didn't find the right hint on the internet, you can help me when you have a look at my specific code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>DataGen App</title>
</head>
<body>
<div>
<h3>Mitarbeiter</h3>
</div>
<div>
<input type="button" value="generateSQL" onclick="generate();" />
<p id="ma" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/mitarbeiter';
function formatItem(item) {
return 'INSERT INTO Mitarbeiter VALUES (' + item.Id + ', ' + item.Name + ', ' + item.Vorname + ', ' + item.Bereich + ');';
}
function generate() {
var str = "";
$.getJSON(uri)
.done(function (data) {
$.each(data, function (key, item) {
str = str + "\n" + formatItem(item);
$('#ma').text(str);
});
})
}
</script>
</body>
</html>
The line break should be generated in the last function.
Thank's a lot and have a nice week!
You can use <br> tag. The <br> tag inserts a single line break.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>DataGen App</title>
</head>
<body>
<div>
<h3>Mitarbeiter</h3>
</div>
<div>
<input type="button" value="generateSQL" onclick="generate();" />
<p id="ma" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/mitarbeiter';
function formatItem(item) {
return 'INSERT INTO Mitarbeiter VALUES (' + item.Id + ', ' + item.Name + ', ' + item.Vorname + ', ' + item.Bereich + ');';
}
function generate() {
var str = "";
$.getJSON(uri)
.done(function (data) {
console.log(data);
$.each(data, function (key, item) {
str = str + "<br>" + formatItem(item);
$('#ma').html(str);
});
})
}
</script>
</body>
</html>

How do I see what data AJAX is passing

I want to be able to see if the data that AJAX is passing is the correct data at the function sendToServer.
When the user submits the data that s/he wants, the submit function sends it to next.php. I want to see what next.php is receiving, how do I do this? It should be receiving the same as here:
$("#result").html(JSON.stringify(arr));
So that I can insert the data into a MySQL database.
next.php:
<?php
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $item;
// insert to db
}
?>
The code that I have so far is in the code snippet:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
Your js is sending a post request therefore you should receive the sent data just as you receive a normal html form post.
try var_dump($_POST); to see under what index names are your data then you can use those index names to manipulate your data as you want.

How to call multiple different AJAX calls to the same div in HTML

so I am reading data from a JSON file. Then I am successfully able to use AJAX calls to update the div in the HTML code. For example:
$("#carSize").append(carInfo[0].carSize);
The div carSize will get the data from the JSON file. However there is going to be 10 different cars with many different properties such as carSize. Since the carInfo array is big and full of several different properties, is there a way to simpler way of my achieving this without having to create a different div to append to for each car's property.
HTML:
<html>
<link href="json.css" rel="stylesheet" type="text/css">
<body>
<div class = "whiteBar">
<div id = "box1">
<div id = "carPrice"></div>
<div id = "carRate"></div>
SELECT
<div id = "total"></div>
</div>
<div id = "box2">
<div id = "carSize"></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="my_script.js"></script>
</body>
</html>
JS
$(document).ready(function()
{
$.getScript("vehicle_data.json", function()
{
$("#carPrice").append(carInfo[0].carPrice + ".00");
$("#carRate").append(carInfo[0].carRate);
$("#total").append("Total: " + carInfo[0].carPrice * 7 + ".00 USD");
$("#carSize").append(carInfo[0].carSize);
});
});
JSON (sample)
var carInfo = [
{
carId: 1,
carPrice : 35.00,
carRate : 'USD/DAY',
carSize : 'Extra Small Car',
type : 'Economy',
},
{
carId: 2,
carPrice : 37.00,
carRate : 'USD/DAY',
carSize : 'Small Car',
type : 'Compact',
}
];
Note how the JS code is just for 1 car and I need it done for 9 other cars. Any ideas?
Could you do something like:
$(document).ready(function(){
$.getScript("vehicle_data.json", function() {
for(i=0; i<carInfo.length; i++){
var $carContainer = $('<div class="carContainer-'+i+'"></div>');
$carContainer.append('<div id="carPrice-'+i+'">'+carInfo[i].carPrice + ".00"+'</div>')
.append('<div id="carRate-'+i+'">'+carInfo[i].carRate+'</div>')
.append('<div id="total-'+i+'">'+"Total: " + carInfo[i].carPrice * 7 + ".00 USD"+'</div>')
.append('<div id="carSize-'+i+'">'+carInfo[i].carSize+'</div>');
$('body').append($carContainer);
}
});
});
Create a new div rather then appending it to existing html
Now that you've stored it in a variable, you can append anything you want to it
$.each(carInfo,function(i,car){
//create a new div to store car info
var myNewDiv = $('<div class="car-info"></div>');
// append car properties to the info div
myNewDiv.append(car.carSive);
myNewDiv.append(car.carId); //etc
// append the new div to existing html
$('.whiteBar').append(myNewDiv);
});
I am not quite sure if this fits what you need but I have had good luck with jsRender http://www.jsviews.com/ for situations like that.
Here is a generic solution if you get all of your cars in one go:
var carInfo = [
{
carId: 1,
carPrice : 35.00,
carRate : 'USD/DAY',
carSize : 'Extra Small Car',
type : 'Economy',
},
{
carId: 2,
carPrice : 37.00,
carRate : 'USD/DAY',
carSize : 'Small Car',
type : 'Compact',
}
];
function getCarHTML (car){
var carHtml = '<div class = "box1" class="car-' + car.carId + '" data-id="' + car.carId + '">' +
'<div id = "carPrice">' + car.carPrice + '</div>' +
'<div id = "carRate">' + car.carRate + '</div>' +
'SELECT' +
'<div id = "total">' + car.carPrice + '</div>' +
'</div>' +
'<div class = "box2">' +
'<div class = "carSize">' + car.carSize + '</div>' +
'</div>';
return carHtml;
};
//this is your ajax on success function
var showCars = function (cars) {
var $carContainer = $('#car-info-container');
cars.forEach(function(car) {
var carHTML = getCarHTML(car);
var $carIfPreset = $carContainer.find('.car-' + car.carId);
if ($carIfPreset.length) {
$carIfPreset.replaceWith(carHTML);
} else {
$carContainer.append(carHTML);
}
});
};
//calling function here, you should make this call inside your ajax
//Assuming ajax to return an array of cars
showCars(carInfo);
Here is a working jsfiddle: https://jsfiddle.net/fjh3mjtm/
Expected json here is {cars: [{carId: 1, carPrice: 35.00, ...}, {carId: 2, carPrice: 37.00, ...}, ...]}

Disappearing list items when sorting/searching w/ list.js

I've built a location search widget using list.js here: http://tonic-agencyhq.co.uk/locations.php
The problem is whenever I search/sort all of the list items disappear. It works fine if I add items in as actual HTML elements but I'm currently using some jQuery+JSON to generate the items.
The code I have used:
<div id="locations">
<input class="search" placeholder="Search" />
<button class="sort" data-sort="location-title">Sort by Title</button>
<button class="sort" data-sort="organisation">Sort by Organisation</button>
<button class="sort" data-sort="city">Sort by City</button>
<ul class="list" id="locations-list"></ul>
</div>
<script src="content/themes/tui/assets/js/jquery.min.js"></script>
<script>
var $locations = $("#locations-list");
$.getJSON("content/themes/tui/assets/json/locations.json", function (locations) {
$.each(locations, function(i, loc) {
var $li = $("<li><h3 class='location-title'>" + loc["Location Title"] + "</h3><p class='organisation'>" + loc["Organisation"] + "</p><p class='address'>" + loc["Address"] + "</p><span class='city'>" + loc["City"] + " | <span class='postcode'>" + loc["Postcode"] + "</span> | <span class='country'>" + loc["Country"] + "</span></li>");
$locations.append($li);
});
});
</script>
<script src="content/themes/tui/assets/js/list.min.js"></script>
<script>
var options = {
valueNames: [ 'location-title', 'organisation' , 'city' ]
};
var locationsList = new List('locations', options);
</script>
<script>
var $locations = $("#locations-list");
$.getJSON("content/themes/tui/assets/json/locations.json", function (locations) {
$.each(locations, function(i, loc) {
var $li = $("<li><h3 class='location-title'>" + loc["Location Title"] + "</h3><p class='organisation'>" + loc["Organisation"] + "</p><p class='address'>" + loc["Address"] + "</p><span class='city'>" + loc["City"] + " | <span class='postcode'>" + loc["Postcode"] + "</span> | <span class='country'>" + loc["Country"] + "</span></li>");
$locations.append($li);
});
var options = {
valueNames: [ 'location-title', 'organisation' , 'city' ]
};
var locationsList = new List('locations', options);
});
Your Ajax call is asynchronous here, move list creation inside this. The dynamic list ($locations.append()) are not getting passed to list.js. That is why you only seeing staically created UL after sort and not dynamically created.

Categories