I have this code which reads the json data below (This code works well):
var data = [{"id":1, "start":"2011-10-29T13:15:00.000+10:00", "end":"2011-10-29T14:15:00.000+10:00", "title":"Meeting"}];
var output = '';
$.each(data, function(index, value){
output += '<li>' + value.title + '</li>';
});
Ive now changed the data (see below) and for some reason it's not working
var data = {"users":[{"firstname":"peter","lastname":"tosh"},{"firstname":"mike","lastname":"Marsh"}]}
var output = '';
$.each(data, function(index, value){
output += '<li>' + value.firstname + '</li>';
});
I know the data format is slightly different ... I'm I forgetting something?
$.each(data.users, function(index, value){
output += '<li>' + value.firstname + '</li>';
});
try this
Although your code is in javascript and not PHP. The problem is that you're having an array inside of an array. So on the first loop your only getting users and not firstName or something like that. Fix:
var data = {"users":
[
{"firstname":"peter","lastname":"tosh"},
{"firstname":"mike","lastname":"Marsh"}
]
}
var output = '';
$.each(data, function(i, users){
$.each(users, function(index, value) {
output += '<li>' + value.firstname + '</li>';
});
});
Related
how can I parse Integer from the JSON file?
Or what is the problem below?
$('#search').keyup(function(){
var searchField = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.getJSON('data.json', function(data){
if(searchField === '') {
$('#update').html('');
return;}
var output ='<ul class="searchresults">';
$.each(data, function(key, val){
if(val.number.search(myExp) != -1) {
output += '<li>';
output += '<p>' + val.number + '</p>';
output += '<p>' + val.name + '</p>';
output += '</li>';
}
});
output += '</ul>';
$('#update').html(output);
});
});
What is missing?
Error is:
Uncaught TypeError: val.number.search is not a function
Many thanks in advance!
Br
Probably it's a number, numbers don't have a search method. You could use .toString().search(...) to convert it to a string first.
I have a bit of a question. which is a loop.
I have a simple looping which when I clicked some numbers and it will search and loop through out my json file.
here is my code
function showSortedRoute(){
$.getJSON('my.json', function(data) {
var $resultHTML = $("#divResult");
var result = "";
result = '<ul class = "list clearfix">';
$.each(data, function (key, val){
if (val.area_id == getRuoute) {
var image = val.image;
var structure_name = val.name;
var copy = val.copy;
var address = val.address;
var access = val.access;
var type = val.type;
var getarea = val.area;
result += '<div class="iconArea">';
result += '<h4>' + name + '</h4>';
result += '<h4><b>' + getarea + '</b></h4>';
result += '</div>';
result += '<p class="catch">' + copy + '</p>';
result += '<dl class="detailArea clearfix">';
result += '<dd>' + address + '</dd>';
result += '<dd>' + access + '</dd>';
result += '</dl>';
result += "</ul>";
$resultHTML.html(result);
} else {
alert("No area ID Found" + getRoute);
}
});
});
}
this does not give me any results, saying no area ID found, but in
alert("no area id found" + getRoute);
and the alert shows displays like four times.
I can check that the value is the same.
code for matching up with integers with json is not working.
There's a few errors in your code:
getRuoute in this line: if(val.area_id == getRuoute){ seems to be
undeclared variable
name in this line: result += '<h4>' + name + '</h4>'; is also
undeclared
getRoute in this line: alert("No area ID Found" + getRoute);
seems to be undeclared variable
Here is corrected and optimized version:
$.getJSON('my.json', function(data) {
var $resultHTML = $("#divResult"),
result = '<ul class = "list clearfix">';
$.each(data, function (key, val){
if (val.area_id == 'getRuoute') { // check type and name of 'getRuote', maybe 'getRoute'?
var image = val.image,
structure_name = val.name,
copy = val.copy,
address = val.address,
access = val.access,
type = val.type,
getarea = val.area;
result += '<div class="iconArea">';
result += '<h4>' + structure_name + '</h4>';
result += '<h4><b>' + getarea + '</b></h4>';
result += '</div>';
result += '<p class="catch">' + copy + '</p>';
result += '<dl class="detailArea clearfix">';
result += '<dd>' + address + '</dd>';
result += '<dd>' + access + '</dd>';
result += '</dl>';
result += "</ul>";
$resultHTML.html(result);
} else {
alert("No area ID Found" + getRoute);
}
});
});
Currently trying to loop through a JSON file and for each object, create a article tag around the data as I format it with HTML, I am successful and creating the first article tag but the I cannot loop through to the next object with the $.each function
HTML code
<body>
<div id='container'>
<div id='content'>
<article class='tumblrPost'>
<header>
<h1> Dragonball Z Motivation </h1>
</header>
<img src='images/dragonball_z.jpg' alt='dragonball z' title='dbz' />
<footer>
<h1> Watch the Video Life & Motivation with Dragonball Z </h1>
</footer>
</article>
</div>
</div>
</body>
</html>
('document').ready(function() {
getPosts();
});
function getPosts() {
var articlePosts = $('div#content article');
$.getJSON('animeTest.json', function(data) {
$.each(data, function(key, val) {
output = "<article>";
output += "<header>";
output += "<h1>" + val.header + "</h1>";
output += "</header>";
output += "<img src='images/" + val.image + "' title='image' />";
output += "<footer>";
output += "<h1>" + val.footer + "</h1>";
output += "</footer>";
output += "</article>";
});
articlePosts.last().after(output);
});
}
You are overwriting output on each cycle
output = "<article>";
Quick fix: try appending the content inside the loop cycle too (and don't declare a global)
$.each(data, function(key, val) {
var output = "<article>";
output += "<header>";
output += "<h1>" + val.header + "</h1>";
output += "</header>";
output += "<img src='images/" + val.image + "' title='image' />";
output += "<footer>";
output += "<h1>" + val.footer + "</h1>";
output += "</footer>";
output += "</article>";
articlePosts.last().after(output);
});
BTW, I feel more comfortable operating on jQuery elements instead of concatenating html. You should try it!
var output = $('<article></article');
var header= $('<header></header');
header.append("<h1>" + val.header + "</h1>").appendTo(output);
output.append("<img src='images/" + val.image + "' title='image' />");
var footer= $ ('<footer></footer>');
footer.append("<h1>" + val.footer + "</h1>").appendTo(output);
articlePosts.last().after(output);
it saves you the pain of closing tags
You're resetting output on each iteration. Technically, you are probably only seeing the last result shown as an article in the HTML.
Instead, declare output right before $.each(), and then only ever append to it. Once you're done looping, append the entire result to your page:
function getPosts() {
var articlePosts = $('div#content article');
$.getJSON('animeTest.json', function(data) {
var output = ''; // make sure you use 'var' so it's not a global variable
$.each(data, function(key, val) {
output += "<article>";
output += "<header>";
output += "<h1>" + val.header + "</h1>";
output += "</header>";
output += "<img src='images/" + val.image + "' title='image' />";
output += "<footer>";
output += "<h1>" + val.footer + "</h1>";
output += "</footer>";
output += "</article>";
});
articlePosts.last().after(output);
});
}
Lastly, if you find yourself building HTML like this often, I would suggest looking into various HTML/JavaScript templating solutions. They would make your JavaScript code far cleaner and easier to maintain by keeping your HTML and JavaScript separate.
I have a getJSON function that looks like below:
$.getJSON("jsonStats.php?action=segment", function(json) {
//Loop over each of the values in the jSON response to make the table.
var tableSegments = '',
counter = 1;
$.each(json, function(key, value) {
tableSegments += '<tr>';
tableSegments += '<td></td>';
tableSegments += '<td>'+counter+'</td>';
tableSegments += '<td>'+value['name']+'</td>';
tableSegments += '<td>'+value['y']+'</td>';
tableSegments += '</tr>';
counter++;
});
$('#segmentTable').empty().append(tableSegments);
});
The issue that I am running into is that its running the each statement/creating the table before it even gets the data. Is there a way to make it wait until it actually has the jSON data before doing that part?
You can use the done callback (jquery.getjson reference) :
$.getJSON('jsonStats.php?action=segment')
.done(function(json)
{
//Loop over each of the values in the jSON response to make the table.
var tableSegments = '',
counter = 1;
$.each(json, function(key, value)
{
tableSegments += '<tr>';
tableSegments += '<td></td>';
tableSegments += '<td>'+counter+'</td>';
tableSegments += '<td>'+value['name']+'</td>';
tableSegments += '<td>'+value['y']+'</td>';
tableSegments += '</tr>';
counter++;
});
$('#segmentTable').empty().append(tableSegments);
})
.fail(function(jqxhr, textStatus, error)
{
var err = textStatus + ', ' + error;
console.log( 'Request Failed: ' + err );
});
Figured it out..
value['name'] and value['y']
need to be value[0] and value[1]
I had the headers as text/javascript on accident this morning so the response was an object, changed it to application/json and thats what made those values change.
I cant seem to get this to work. Im trying to do two things
A). Get the following code to show up correctly. The first element is show 'undefined
<ul>
<li>Button
<ul>
<li>x:1</li>
<li>y:2</li>
<li>width:3</li>
<li>height:4</li>
</ul>
</ul>
Here is my code:
$(document).ready(function() {
var data = {
"Controls": [{
"Button":[{ "x": "1","y": "2","width": "3","height": "4" }],
"Image":[{"x": "5","y": "6","width": "7","height": "8"}],
"TextField":[{"x": "9","y": "10","width": "11","height": "12"}]
}]
}
var str = '<ul>';
$.each(data.Controls, function(k, v) {
str += '<li>' + k[0] + '</li><ul>';
for(var kk in v.Button[0]){
str += '<li>' + kk + ':' + v.Button[0][kk] + '</li>';
}
str += '</ul>';
});
str += '</ul>';
$('div').append(str);
})
And
B). trying to display a list(separate list from above) of just the fields. like this:
<li>Button</li>
<li>Image</li>
<li>TextField</li>
I think that the answer to the second lies in the first, but I cannot seem to get the targeting right.
Any help is appreciated
Demo
To get the first list:
var str = '<ul>';
var target = "Button";
str += '<li>' + target + '<ul>';
$.each(data.Controls[0][target][0], function(kk, vv){
str += '<li>' + kk + ':' + vv + '</li>';
});
str += '</ul></li>';
str += '</ul>';
To get the second list:
var str = '<ul>';
$.each(data.Controls[0], function(k,v) {
str += '<li>' + k + '</li>';
});
str += '</ul>';
To target them by index, so Button is 0:
var str = '<ul>';
var target = 0;
var count = 0;
$.each(data.Controls[0], function(k,v) {
if(count == target)
{
str += '<li>' + k + '<ul>';
$.each(v[0], function(kk, vv){
str += '<li>' + kk + ':' + vv + '</li>';
});
str += '</ul></li>';
return false; // <-- break because we got what we wanted
}
count++;
});
str += '</ul>';
First of all, this has nothing to do with JSON. JSON is a string-serialization format. What you have here is an object literal.
Second, I have no idea why you are wrapping all your object definitions inside Controls, with arrays, seems like a lot of extra hassle. You are also doing things in a very non-jQuery way.
You could try something like this:
var data = {
"Controls": {
"Button":{ "x": "1","y": "2","width": "3","height": "4" },
"Image":{"x": "5","y": "6","width": "7","height": "8"},
"TextField":{"x": "9","y": "10","width": "11","height": "12"}
}
}
$('div').append('<ul id="outer_ul">');
$.each(data.Controls, function(key, value) {
$('#outer_ul').append('<li>' + key + '</li>', '<ul id="' + key +'">');
$('#field_list').append('<li>' + key + '</li>');
$.each(value, function(key2, value2) {
$('#' + key).append('<li>' + key2 + ':' + value2 + '</li>');
}
}
This code populates both you div as well as a ul with the id of field_list which would represent the container into which you want to put the second list (so adjust this code according the the proper jQuery selector you want to use.