Output JSON to HTML - javascript

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!

Related

How to append json object to the table through ajax with time delay in jquery?

I'm new to js & jquery, I am create a json object to display the data in table through external json. But i want to add data in the json file, the data automatically updated in the table.
$(window).load(function(){
$(document).ready(function () {
var url='json/data.json';
$.getJSON(url, function (r) {
for (var i = 0; i < r.length; i++) {
var tr = $('<tr>');
tr.append("<td>" + r[i].User_Name + "</td>");
tr.append("<td>" + r[i].score + "</td>");
tr.append("<td>" + r[i].team + "</td>");
$('tbody').append(tr);
}
});
});
});
<table id="racer_details">
<tbody>
</tbody>
</table>
my json data is,
[
{
"User_Name":"John Doe",
"score":"10",
"team":"1"
},
{
"User_Name":"Jane Smith",
"score":"15",
"team":"2"
},
{
"User_Name":"Chuck Berry",
"score":"12",
"team":"2"
}
]
This is my sample data, first i add 3 values to the table but i want to update the values to the table with time delay, if i want to add some values in json it will automatically update values in the table after time delay. How is it possible with jquery with ajax.
HTML:
<table id="racer_details">
<tbody id="racer_data">
</tbody>
</table>
JS: You can show data like this using ajax,
$(window).load(function(){
$(document).ready(function () {
$.ajax({
type:"GET",
url:"xyz",
data:{ 'xyz': xyz },
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function (result){
var dataTab = $.parseJSON(JSON.stringify(result));
$.each(dataTab.data, function (index, value) {
$("#racer_data").append('<tr>'+value.name+'</tr>
<tr>'+value.scor+'</tr>
<tr>'+value.team+'</tr>'
},
error: function(){},
});
});
});

retrieving data from jsonp api that contains pages

I'm a little stuck on how I can retrieve all data from a jsonp api when the data is split in pages. The callback looks like this:
{
entries: [],
page: 1,
pages: 101,
posts: 10054
}
the code under only gets me results from page 1, but I would like to get results from all 101 pages. If I add a query to the url like : &page=2 or &page=3 I can access objects from that page only, what I'm trying to is access all objects from all pages in one go....
would appreciate some help :)
$.getJSON('http://hotell.difi.no/api/jsonp/mattilsynet/smilefjes/tilsyn?callback=?', function(data){
var html = "";
$.each(data.entries, function(key,value){
html += '<p>' + value.navn + '</p>';
})
$('#test').html(html);
})
You can make first call to get the number of pages and in next calls you can loop through them.
Try below code
$.getJSON('http://hotell.difi.no/api/jsonp/mattilsynet/smilefjes/tilsyn?callback=?', function(data) {
var pages = data.pages;
for (var i = 1; i <= data.pages; i++) {
$.getJSON('http://hotell.difi.no/api/jsonp/mattilsynet/smilefjes/tilsyn?callback=?&page=' + i, function(data) {
$('#test').append("Page " + data.page + " Data >> ");
var html = "";
$.each(data.entries, function(key, value) {
html += '<p>' + value.navn + '</p>';
})
$('#test').append(html);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>
You can use jsonp using $.ajax() not by $.getJSON(). and you have to declare your callback method in your javascript code
$("#btn").click(function(){
$.ajax({
url: "http://hotell.difi.no/api/jsonp/mattilsynet/smilefjes/tilsyn?callback=myJsonpCallbackMethod",
dataType: "jsonp",
success: function( response ) {
//console.log( response ); // server response
}
});
});
function myJsonpCallbackMethod(data){
alert("Hello");
console.log( data ); // server response
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button id="btn">Click Me</button>

Can't retrieve data in table from json

I am trying to load data into table using JQuery and AJAX but when I click on the button data is not retrieved. I have done coding as shown below:
var globalgrid;
Here I am going to call json url and try to display it in the table.
function loadgrid() {
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://instatalk.in/sip/GetApprovedUsersList?page=1&limit=10',
success: function(griddata) {
globalgrid = griddata.lines;
// remove all data - but the headers!
$("#gridtable").find("tr:gt(0)").remove();
if (globalgrid.length === 0) {
$('#errormsg').html('Sorry, <strong>no</strong> rows returned!');
return;
}
for (var i = 0; i < globalgrid.length; i++) {
var line = globalgrid[i];
// insert after last row!
$('#gridtable > tbody:last').append('<tr><td>' + line.Id + '</td><td>' + line.AccountId + '</td><td>' + line.Name + '</td><td>' + line.IsFranchiseUser + '</td></tr>');
}
},
error: function(data, errorText) {
$("#errormsg").html(errorText).show();
}
});
}
I am getting the table heading only. When I click on the button I want data to be retrieved from the json data. I don't know where I am going wrong. Please do help.
This is my json file:
{"results":[{"Id":17,"AccountId":"5737329468","Name":"Martin (Nigeria)","IsFranchiseUser":false},{"Id"
:16,"AccountId":"3644824444","Name":"Deep Patel","IsFranchiseUser":false},{"Id":15,"AccountId":"4692068407"
,"Name":"Jacob (kiribati)","IsFranchiseUser":false},{"Id":14,"AccountId":"4650982975","Name":"sebin John
(spain)","IsFranchiseUser":false},{"Id":13,"AccountId":"2855375107","Name":"Jassi want(new jersey)"
,"IsFranchiseUser":false},{"Id":12,"AccountId":"6242007588","Name":"Moussa","IsFranchiseUser":false}
,{"Id":11,"AccountId":"3075258818","Name":"srkrbm (saudi arab)","IsFranchiseUser":true},{"Id":10,"AccountId"
:"3615509810","Name":"Om Saini","IsFranchiseUser":false},{"Id":9,"AccountId":"9251133143","Name":"swati
mohandas","IsFranchiseUser":false},{"Id":8,"AccountId":"8143395019","Name":"babu Kuppu","IsFranchiseUser"
:false}],"totalAccounts":16}
This line: globalgrid = griddata.lines;
According to your Json data format, you should use griddata.results.

How do I extract data from xml and post to a div using jquery/javascript

I am trying to get the title for a twitch.tv stream from an xml file using either jQuery or JavaScript and then post that title to a div (as a section header). The title is found in the <status> section of the xml file.
Below the code I currently have which doesn't seem to be working:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://www.twitch.tv/meta/koibu.xml",
dataType: "xml",
success: function(xml) {
var xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$(xml).find('meta status').each(function(){
$('#block').append("<h2>" + $(this).text() + "</h2>");
});
}
});
});
Here is a jsfiddle -with my broken script in- to play with.
Edit: solved it using a json call instead of reading xml
$(document).ready(function(){
var names = ["koibu"];
var obj = jQuery.parseJSON('{"name": {"life": "{life}","logo": "{logo}","status": "{status}","preview": "{preview}","url": "{url}"}}');
grabJSON();
function grabJSON() {
setTimeout(grabJSON,1000);
for (index = 0; index < names.length; ++index) {
$.getJSON("https://api.twitch.tv/kraken/channels/" + names[index] + "/?callback=?", function (json) {
$('#lefttitle').empty(),
$('#lefttitle').append("<h2>" + json.status + "</h2>");
});
}
}
});
This also allows me to set up a nice little array to grab more data from multiple channels if I want to extend it in future.
If you're not suffering from CORS, then the actual problem is below
$(xml).find('status').each(function(){
$('#block').append("<h2>" + $(this).text() + "</h2>");
});
xml variable represents the unparsed XML.
It has to like
$xml = $(xmlDoc);
$xml.find('status').each(function(){
$('#block').append("<h2>" + $(this).text() + "</h2>");
});
I managed to get your XML file, and the status tag contains Monday Mafia!

ajaxing data and displaying

I am trying to display some xml data from remote URL using jquery and ajax. In my xml, there are simply two elements to be accessed: title and url.
The structure of my xml file is as follows:
<list>
<lists>
<songs>
<title>Pumped Up Kicks - Foster the people</title>
<url>http://dc249.4shared.com/img/970884399/8b9afc1d/dlink__2Fdownload_2Fmf4- 10b_5F_3Ftsid_3D20111122-112912-f675aa20/preview.mp3</url>
</songs>
</lists>
</list>
And I have the following jquery code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://jeewanaryal.web44.net/SongsXML/nepaliSongs.xml",
dataType: "xml",
success: function (xml) {
var items = parseXml(xml);
doStuff(items);
}
});
});
function parseXml(xml) {
var items = [];
$(xml).find("songs").each(function () {
items.push({
name: $(this).find("title").text(),
value: $(this).find("url").text()
});
});
for (var i = 0; i < items.length; i++) {
$(".phoneGapAPI").append(items[i].name + " <button class=\"newsDiv\" onclick=\"openChildBrowser(" + items[i].value + ");\">click here</button> <br> <br />");
}
}
I can guess that I am doing wrong at the statement openChildBrowser("+items[i].value+");
How can I implement this? I need to pass the variable items[i].value inside the function openChildBrowser().
This code works fine displaying items[i].name but click here link does not let me to open that URL.
Jquery failed to to render your Xml (Error : XML Parsing Error: no element found Location: moz-nullprincipal:{9e622e17-2e96-4a4d-95e4-6f7b95d0b4d8} Line Number 1, Column 1:) .Try to add version information to that xml file.
like
<?xml version="1.0" encoding="ISO-8859-1"?>

Categories

Resources