How to Print parsed JSON data in HTML page in a table - javascript

I have accessed the JSON data through web service call and parsed the JSON data. I would like to know how to print that JSON data in HTML table???
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Download</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function jsonparser1() {
$.ajax({
type: "GET",
crossDomain: true,
url: "http://10.211.2.219:8080/JerseyWebService/rest/sample/files",
dataType: "jsonp",
success: function (res) {
$.each(res['data'], function (i, row) {
var ftime = row['time'];
var fname = row['name'];
var fhref = row['href'];
document.myform.???????????????=ftime;
??????????????????????????????????????
??????????????????????????????????????
})
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
</head>
<body>
<form name="myform">
<input type="button" name="clickme" value="Click here to display the details of the files" onclick=jsonparser1() />
??????????????????????????????????????????
??????????????????????????????????????????
</form>
</body>
</html>
The JSON data i am using is:
{"data":[{"id":13,"time":"02-08-2012 3:24:45 PM","name":"jersey-multipart-1.0.3.144640.jar","href":"file://chndlf716168/TempUp/1343901285087-FileName-jersey-multipart-1.0.3.144640.jar"},{"id":14,"time":"02-08-2012 3:36:0 PM","name":"icloud_hero.png.png","href":"file://chndlf716168/TempUp/1343901960304-FileName-icloud_hero.png.png"}],"code":true}
I would like to display the time,name and href attributes in a table format. The href should be in anchor tag. If more number of data are appended into JSON file means, the table should be flexible to change. First step is that i have to display the details in table format.
Anybody please helpout in this thing... Thanks in advance...

Hope this helps:
$("document").ready(function() {
$.getJSON("http://localhost:1909/encoders", function(data) {
$("#div-my-table").text("<table>");
$.each(data, function(i, item) {
$("#div-my-table").append("<tr><td>" + item.EncoderName +"</td><td>" + item.EncoderStatus + "</td></tr>");
});
$("#div-my-table").append("</table>");
});
});

Try this out
var output = "<table>";
$.each(res['data'], function (i, row) {
var ftime = row['time'];
var fname = row['name'];
var fhref = row['href'];
output+="<tr><td>VARIABLE VALUE</td></tr>";
})
output += "</table>";
When the outpur variable is ready with the content. Print it in the desire location.

This is basic jquery in your each loop do this.
$row = $('<tr></tr>');
$row.append('<td>' + somedata + '</td>');
// repeat the above line for each data item
$('#mytable).append($row);
In your HTML create <table id="mytable"></table>

Related

How do I get asp-items to populate a select when adding select element to a div?

Using Javascript to add a select dropdown list when a button is clicked, but the select isn't being populated with the data from the viewmodel. Essentially this code creates what I want, but the asp-items are not populating the select aside from the default "Select Column Name" option.
How would I get this asp-items to populate from the viewmodel selectlist, "Model.SelColumnNames"?
<script>
$('.addSort').click(function() {
$('.block:last').before('<div class="block"><select asp-for="SelColumnNameAdditional" asp-items="Model.SelColumnNames" style="width: 30%;"><option value="">Select Column Name</option></select>   <select style="width: 15%;"><option value="1">Ascending</option><option value="2">Descending</option></select>   <span class="remove">Remove Option</span></div>');
});
</script>
Edit:
I can already populate it properly as a dropbox in the HTML section of my viewpage using this:
<select asp-for="SelColumnNameAdditional" asp-items="Model.SelColumnNames" style="width: 30%;">
<option value="">Select Column Name</option>
</select>
I would like the script code to be able to create a div with the same populated dropdown in javascript. When I do that, asp-items doesn't pull from the viewmodel like it does in the HTML code. Why is that?
If you are using Javascript, you need to get data using ajax. This is what I have so far.
Controller/ViewModel
public class JaesonViewModel
{
public string value { get; set; }
public string text { get; set; }
}
public class HomeController : Controller
{
public ActionResult GetViewModel()
{
var list = new List<JaesonViewModel>();
var j = new JaesonViewModel { text = "text1", value = "value1" };
list.Add(j);
var j2 = new JaesonViewModel { text = "text2", value = "value2" };
list.Add(j2);
return Json(new { Items = list.ToList() }, JsonRequestBehavior.AllowGet);
}
public ActionResult Index10() //I am calling index10 to start--the view is index10
{
return View();
}
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index10</title>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(function () {
$('.addSort').click(function () {
$.ajax({
type: "GET",
url: "/home/GetViewModel",
async: false,
cache: false,
dataType: "json",
contentType: "application/json",
success: function (jsn) {
jQuery.each(jsn.Items, function (index, itemData) {
$('.dropdown').append('<option value=' + itemData.value + '>' + itemData.text + '</option>');
});
},
error: function (jqXHR, exception) {
var status = jqXHR.status; //400
var message = jqXHR.responseText;
var ex = exception; // 'abort' for example
alert(status + " " + message + " " + ex);
}
});
});
});
</script>
</head>
<body>
<input type="button" class="addSort" value="Click Me" />
<select class="dropdown">
</select>
</body>
</html>

Output JSON to HTML

I am able to pull some data if I input the json manually into the JS...however, I am trying to pull it from a seperate file ('mindshare.json') and populate only certain fields (title, content, featured image).
When I use the code below, I get 3 columns of "undefined".
My question is, how do I:
Reference the ID of the post that will contain the title, content, image?
Do I have to add any other code to json file to call the nested tags?
Im a JSON noob, so I appreciate your patience.
Here's my code:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
var json = "mindshare.json";
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + json[i].title + "</td>");
tr.append("<td>" + json[i].content + "</td>");
tr.append("<td>" + json[i].source + "</td>");
$('.mindshare').append(tr);
}
});
</script>
<div class="mindshare">
</div>
</body>
</html>
The JSON file can be found at http://toolboxwebdesign.com/mindshare.json.
$.ajax({
dataType: "json",
url: 'http://toolboxwebdesign.com/mindshare.json',
success: function(result){
var json = JSON.stringify(result);
json = JSON.parse(json);
}
});
Now you should have your JSON values in the json variable
*There are some cases in which the ajax call with the json datatype does not give a valid json and it should be parsed to a string and back again to object to work.
Here's how you load the data from your json file and turn it into an HTML table :
function arrayToTable(tableData) {
var table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData.title+'</td>'));
row.append($('<td>'+cellData.content+'</td>'));
row.append($('<td>'+cellData.source+'</td>'));
});
table.append(row);
});
return table;
}
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://toolboxwebdesign.com/mindshare.json",
dataType: 'json',
success: function (data) {
$('.mindshare').append(arrayToTable(data));
}
});
});
Notes
You can't run AJAX calls locally. If you're running it on your laptop or desktop computer, you need to have a web server running.
Your json file needs to be hosted at the same domain as your JS code.
Your json needs to be valid. According to JSONLint, it is not!

ajax-loading doesn't stop or infinite loop?

I'm not sure if it is an ajax issue or if I have an infinite loop, I'm trying to get the values of one page to another.
My 1st page is a cakephp contoller:
$arr = ($this->Phone->find('all'));
$arr2 = json_encode($arr);
echo $arr2;
$_GET ['var1'] = $arr2;
die();
My 2nd page that gets and displays the output is this one
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="sizeof.js"></script>
<script type="text/javascript">
var results;
{
$.ajax({
type: 'GET',
url: 'http://localhost/restdemo/',
data: {
var1: results
},
success: function(data) {
console.log('success');
var output = JSON.parse(data);
for (x = 0; x <= output.length - 1; x++) {
var hello = (output[x]["Phone"]["name"]);
document.write('<table border="1" cellspacing="1" cellpadding="5">');
document.write('<tr>');
document.write('<td>' + hello + '</td>');
document.write('</tr>');
document.write('</table>');
}
}
});
}
</script>
</head>
<body>
</body>
</html>
I am getting my desired results however the page doesn't stop loading which makes me think that I have an error in my code to cause such an action. What causes this?and how can I fix it?. any feedback, comments and suggestion is highly appreciated.

on click event I am trying to get the data from XML as per the click object's attr() value

on click event I am trying to get the data from XML as per the click object's attr() value.
Below I have placed two hyperlink buttons and a container for input the data. Both are having different attr() value.
So I want to get the data according to these hyperlink's attr() value.
Even I have created a XML with respective nodes.But unable to get the exact data. can anyone please help?
here is the JS and XML code:
JS Code:
$(function() {
$('a.readmore').click(function() {
var container = $('#uiWrapper');
$.get('myxml3.xml',function(data){
container.empty();
$(data).find('sector').each(function(){
var $tag = $(this),
getName = $('a.readmore').attr('href');
var html = '<div class="data">';
html += '<div class="tagDetail">' + $tag.find('description').text() + '</div>';
html += '</div>';
if($tag.attr('name') == getName){
container.append(html);
}else{
return false;
}
});
});
return false;
});
});
XMLCode:
<?xml version="1.0" encoding="utf-8" ?>
<sections>
<sector name="mark">
<description>Mark Text is coming</description>
</sector>
<sector name="source">
<description>Source Text is coming</description>
</sector>
</sections>
If you want by clicking on the link the description is display according to the href attribute of the link, your html page with script will be
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var container = $('#uiWrapper');
$('a.readmore').click(function(e){
e.preventDefault();
var getName=$(this).attr('href')
container.empty();
$.get('myxml3.xml', function(xml){
$(xml).find('sector').each(function(){
var $sector = $(this);
var title = $sector.attr("name");
if(title===getName){
var description = $sector.find('description').text();
var html='<div class="data"><div class="tagDetail">'+description+'</div></<div>'
$('#uiWrapper').append($(html));
};
});
});
});
});
</script>
</head>
<body>
<div id="uiWrapper"></div>
<a class="readmore" href="mark">mark</a>
<a class="readmore" href="source">source</a>
</body>
</html>
For this example i use the xml file of your post
If you want to get the same result by using the $ajax method, your code will be
<script type="text/javascript">
$(document).ready(function(){
var container = $('#uiWrapper');
$('a.readmore').click(function(e){
e.preventDefault();
var getName=$(this).attr('href')
container.empty();
$.ajax({
type: "GET",
url: "myxml3.xml",
dataType: "xml",
success: function (xml) {
var xmlDocument = $.parseXML(xml)
var $xml = $(xmlDocument);
$(xml).find('sector').each(function(){
var $sector = $(this);
var title = $sector.attr("name");
if(title===getName){
var description = $sector.find('description').text();
var html='<div class="data"><div class="tagDetail">'+description+'</div></<div>'
$('#uiWrapper').append($(html));
}
})
}
});
});
});
</script>

How to read xml file contents in jQuery and display in html elements?

I am new to Jquery.I am trying to read data from "sampleXML.xml" file and display that data in Html "li" elements. so far I have done is, I have created html file as follows:file name-"Cloudtags.html":
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script src=Cloudtags.js></script>
<title>Css Globe: tag clouds</title>
<link rel="stylesheet" type="text/css" href="Cloudtags.css">
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<div id="container">
<script type="text/javascript" src="http://cssglobe.com/ads/blogsponsor.js"></script>
<div id="side">
<div class="tags">
<ul class="cld">
<li class="tag1" id="java">google</li>
<li class="tag2">Chiessy</li>
<li class="tag3">sitemap</li>
<li class="tag2">Sales</li>
<li class="tag4" >Gohome</li>
<li class="tag1"id="temp">Movies</li>
<li class="tag1">It Jobz</li>
<li class="tag5">Alza</li>
<li class="tag2">Sea food</li>
<li class="tag1">Hospital</li>
<li class="tag3">Smart phone</li>
<li class="tag4">Pizza </li>
<li class="tag1">Aerobics</li>
<li class="tag5">Yahoo...</li>
<li class="tag1">Anti-Virus</li>
<li class="tag2">Travel</li>
</ul>
</div>
</div>
<div id="xmldata"></div>
</div><br>
</body>
</html>
and this is my .js file:
$(document).ready(function() {
var nm;
$.ajax({
type: "GET" ,
url: "sampleXML.xml" ,
dataType: "xml" ,
success: function(xml) {
$(xml).find('person').each(function() {
nm= $(this).text()
$("#temp").html(nm);
}
}
});
});
My xml file is as follows:
<?xml version='1.0' ?>
<doc>
<person>
<name>sachin</name>
<age>21</age>
</person>
<person>
<name>Akash</name>
<age>18</age>
</person>
</doc>
But this does not work. Do I need to link some external file for "$.ajax". Where is my mistake?
I think you want like this, DEMO
var xmlDoc = $.parseXML( xml );
var $xml = $(xmlDoc);
var $person = $xml.find("person");
$person.each(function(){
var name = $(this).find('name').text(),
age = $(this).find('age').text();
$("#ProfileList" ).append('<li>' +name+ ' - ' +age+ '</li>');
});
Simply you can read XML file as dataType: "xml", it will retuen xml object already parsed. you can use it as jquery object and find anything or loop throw it…etc.
$(document).ready(function(){
$.ajax({
type: "GET" ,
url: "sampleXML.xml" ,
dataType: "xml" ,
success: function(xml) {
//var xmlDoc = $.parseXML( xml ); <------------------this line
//if single item
var person = $(xml).find('person').text();
//but if it's multible items then loop
$(xml).find('person').each(function(){
$("#temp").append('<li>' + $(this).text() + '</li>');
});
}
});
});
jQuery docs for parseXML
First of all create on file and then convert your xml data in array and retrieve that data in json format for ajax success response.
Try as below:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "sample.php",
success: function (response) {
var obj = $.parseJSON(response);
for(var i=0;i<obj.length;i++){
// here you can add html through loop
}
}
});
});
sample.php
$xml = "YOUR XML FILE PATH";
$json = json_encode((array)simplexml_load_string($xml)),1);
echo $json;
You can use $.each()
Suppose your xml is
<Cloudtags><id>1</id></Cloudtags><Cloudtags><id>2</id></Cloudtags><Cloudtags><id>3</id></Cloudtags>
In your Ajax success
success: function (xml) {
$(xml).find('Cloudtags').each(function(){// your outer tag of xml
var id = $(this).find("id").text(); //
});
}
For your case
success: function (xml) {
$(xml).find('person').each(function(){// your outer tag of xml
var name = $(this).find("name").text(); //
var age = $(this).find("age").text();
});
}
responseText is what you are looking for. Example:
$.ajax({
...
complete: function(xhr, status) {
alert(xhr.responseText);
}
});
Where xml is your file. Remember this will be your xml in the form form of a string. You can parse it using xmlparse as some of them mentioned.
$.get("/folder_name/filename.xml", function (xml) {
var xmlInnerhtml = xml.documentElement.innerHTML;
});
Get the XML using Ajax call, find the main element, loop through all the element and append data in table.
Sample code
//ajax call to load XML and parse it
$.ajax({
type: 'GET',
url: 'https://res.cloudinary.com/dmsxwwfb5/raw/upload/v1591716537/book.xml', // The file path.
dataType: 'xml',
success: function(xml) {
//find all book tags, loop them and append to table body
$(xml).find('book').each(function() {
// Append new data to the tbody element.
$('#tableBody').append(
'<tr>' +
'<td>' +
$(this).find('author').text() + '</td> ' +
'<td>' +
$(this).find('title').text() + '</td> ' +
'<td>' +
$(this).find('genre').text() + '</td> ' +
'<td>' +
$(this).find('price').text() + '</td> ' +
'<td>' +
$(this).find('description').text() + '</td> ' +
'</tr>');
});
}
});
Fiddle link: https://jsfiddle.net/pn9xs8hf/2/
Source: Read XML using jQuery & load it in HTML Table

Categories

Resources