Use $.each and if with $.getJSON - javascript

Me and $.each aren't good friends, I can't seem to figure out how I should use this statement to print all my data in my JSON file. Another problem is the if statement, I tried it in many ways, but whatever I do, no data is being printed.
My JSON file
[
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"exp1_index.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"exp2_index.html"
}
]
My $.getJSON script
<script type="text/javascript">
function read_json() {
$.getJSON("home.json", function(data) {
var el = document.getElementById("kome");
el.innerHTML = "<td><div class='dsc'>" + data.expo + "<br><em>" + data.datum + "</em></div></td>";
});
}
</script>
So how would I integrate the $.each statement and seperate from that, the if statement?

Try this
$.getJSON("home.json", function (data) {
var html = '',
el = document.getElementById("kome");
$.each(data, function (key, val) {
html += "<td><div class='dsc'>" + val.expo + "<br><em>" + val.datum + "</em></div></td>";
});
el.innerHTML = html;
});

Something like this?
<script type="text/javascript">
function read_json() {
$.getJSON("home.json", function(data) {
var html = '';
$.each(data, function(i, record) {
html += '' +
'<td>' +
'<a href="' + record.link + '" data-ajax="false">' +
'<img src="' + record.img + '">' +
'<div class="dsc">' +
record.expo + '<br>' +
'<em>' + record.datum + '</em>' +
'</div>' +
'</a>' +
'</td>';
});
$('#kome').html(html);
});
}
</script>
Note: I haven't tested this, so there may be a few syntax errors (mostly concerned about the quotes in the string concatenation).
I will note that you don't need jQuery's $.each for this; you can use a basic for-loop:
for (var i = 0; i < data.length; i++) {
var record = data[i];
... stuff...
}
jQuery's .each() is really useful when iterating over elements in the DOM, though. For example, if you wanted to iterate over the elements with class dsc, you could do:
$('.dsc').each(function(i, dsc) {
// Do stuff to the $(dsc) element.
});
Also, you might as well use jQuery's selectors (the $('#kome')) if you're going to use jQuery.
jQuery's API usually has solid examples for stuff; this is one such case.

$.each can iterate arrays [] or objects {}, your json contains both, so first you need to tackle array, that gives you an object on each iteration. Then you can access its properties.
jQuery each documentation
Second thing: to append to innerHTML use "+=" not "=" or you will reset html on each iteration.
var el = document.getElementById("kome");
$.getJSON('ajax/test.json', function(data) {
$.each(data, function(n, linkData) {
el.innerHTML += '' + linkData.expo + '';
});
}

Related

Why always getting last row from json array result when iterate through with Jquery

I have json data in this structure
here is my json code
https://jsonblob.com/309e8861-7f26-11e7-9e0d-cf3972f3635e
and here is my jquery code example
$("#getJsonData").click(function(){
$.get(base_url + 'roles/index', function(data) {
var data = $.parseJSON(data);
$.each(data, function(index, val) {
$("#result").html("<p>" + val.name + "</p>");
});
});
});
HTML file
<button id="getJsonData">Load role list</button>
<div id="result"></div>
I don't get this, I get every value from json in console when do console.log, but when use html method to display result as html in screen it just showing last value from ending last json array. What is wrong here?
jquery .html always overrite previous html so we cant use html in loop section instead of that we can use append it simply append your p tag in result div
Instead of using this:-
$("#result").html("<p>" + val.name + "</p>");
use like this:-
$("#result").append("<p>" + val.name + "</p>");
You are overwriting the html with the code
$("#result").html("<p>" + val.name + "</p>");
Instead you can store the result in variable and then you write it to the element.Like this
$("#getJsonData").click(function(){
$.get(base_url + 'roles/index', function(data) {
var data = $.parseJSON(data);
var html = '';
$.each(data, function(index, val) {
html +="<p>" + val.name + "</p>";
});
$("#result").html(html);
});
});
Your code should be :
$("#getJsonData").click(function(){
$.get(base_url + 'roles/index', function(data) {
var data = $.parseJSON(data);
var listHtml="";
$.each(data, function(index, val) {
listHtml=listHtml+ "<p>" + val.name + "</p>";
});
$("#result").html(listHtml);
});
});
And Html should be same as your
<button id="getJsonData">Load role list</button>
<div id="result"></div>
Working example is here

PHP generated option list only appearing on first Ajax dynamically generated container

I am having an issue where my php generated select/option list is not applying to all of my dynamically generated blocks/containers. It only adds the PHP select to the last container/block instance, despite being called for each container. When troubleshooting with alerts it seems to run through all of the iterations prior to adding the containers/blocks and generating the select, hence why it always appears on the last only-
n = -1
function addDiv() {
n++;
So, a brief overview - on page initialize the code will get how many entries are in the database within a certain criteria and apply that number to 'length', which then runs the function addDiv() that many times. Usually, when adding a block one at a time via button it will populate the created block with a Select/list of Options via php in the addDiv() function, however when automating this with a loop ( the initialize() function ) the above issue occurs.
$( document ).ready(function() {
initialize();
});
function initialize() {
$.ajax({
url: 'get-entries.php',
type: 'POST',
dataType: 'text',
cache: false,
success: function(data) {
result = data;
var arrayJson = JSON.parse(data);
console.log(arrayJson);
length = arrayJson.length;
console.log(length);
for(var i = 0; i < length; i++) {
addDiv();
};
},
error: function(jqXHR) {
alert("Error while fetching data");
console.log("Error while fetching data: " + jqXHR.status + " " + jqXHR.statusText + " " + jqXHR.responseText); //improved error logging
}
});
};
here is the addDiv related code with some redactions to make it easier to read.
var n = -1;
function addDiv() {
n++;
$.post(
"json-option-generator.php",
{}
).done(
function(data)
{
$('#selectedcoin' + n).html(data);
});
$("<div class='coinmarketcap fill' id='container"
+ n +
"'><form id='"
+ n +
"' name='"
+ n +
"' class='formClass' method='post' action=''><select onchange='mySelect(this)' type='text' class='coinname' id='selectedcoin"
+ n +
"' name='selectedcoin"
+ n +
//.etc.....
"' autocomplete='off' value=''><select></select>").appendTo(".main-container");
}
and finally here is the contents of the PHP file for generating the option list based off of json data -
<?php
$json = file_get_contents("../ticker/full.json");
$decode = json_decode($json, true);
sort($decode);
echo '<select name="coinname">';
foreach($decode as $a){
echo "<option value='{$a['id']}'>{$a['name']}</option>";
}
echo '</select>';
?>
I know this is messy and may require a bit of an in depth read through, so I appreciate anyone taking the time to look.
Is there anything glaringly obvious that can help nudge me in the right direction? I have tried breaking the 'addDiv()' calls within initialize() by wrapping 'addDiv()' with a setTimeout function, but no joy.
it should work with this (I named the arguments differently for comprehension, but index and index_t can all be named n):
var n = -1;
function sendToGenerator(index){
var index_t = index;
$.post(
"json-option-generator.php",
{}
).done(
function(data)
{
$('#selectedcoin' + index_t).html(data);
}
);
}
function addDiv() {
n++;
sendToGenerator(n);
$("<div class='coinmarketcap fill' id='container"
+ n +
"'><form id='"
+ n +
"' name='"
+ n +
"' class='formClass' method='post' action=''><select onchange='mySelect(this)' type='text' class='coinname' id='selectedcoin"
+ n +
"' name='selectedcoin"
+ n +
//.etc.....
"' autocomplete='off' value=''><select></select>").appendTo(".main-container");
}

How to append data for each div separately

Simple but I dont know how to do it. I am trying to append data for each div separately $. Each function is looping and assigning whole data to the same div.
These are my two div.
<div class="div1">
<div class="div2">
// whole javascript code is here
</div>
</div>
The whole code is something like this:
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function(data)
{
htmlResultData="<br /> " + "Users received from server: " + "<br />";
$.each(data, function (i, item)
{
htmlResultData += item.PostedByName + "<img src='" + item.PostedByAvatar + "'height='100' width='100'/> ";
});
$(".div2").empty().append(htmlResultData);
//however, i have tried to return false here but still same result
return false;
});
});
Div1 contains outer CSS for that particular div2. I want to generate multiple div2 for each data returned from the server. I have tried using return false but still same result. Please tell me how to do it.
This may help you. I have change the code to make it simple.
$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function (data) {
//make parent div blank
$(".div1").html("");
$.each(data, function (i, item) {
//make html for div2
var html += "<div class='div2'>";
html += item.PostedByName;
html += "<img src='" + item.PostedByAvatar + "'height='100' width='100'/>"
html += "</div>";
//append all div2 to parent div1
$(".div1").append(html);
});
});
});
$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function(data)
{
htmlResultData="<br /> " + "Users received from server: " + "<br />";
$.each(data, function (i, item)
{
htmlResultData +="<div class='div2'> item.PostedByName + "<img src='" + item.PostedByAvatar + "'height='100' width='100'/></div> ";
});
$(".div1").empty().append(htmlResultData);
//however, i have tried to return false here but still same result
//return false;
});
});

Extracting user playcount from Last.fm API using JSON

In a nutshell, I'd like to display the Last.fm user playcount figure on my site (see 'playcount' on http://www.last.fm/api/show/user.getInfo). I've tried the following, but confess I have no idea if I'm on the right lines here.
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user=XXX&api_key=XXX&limit=5&format=json&callback=?", function(data) {
var html = '';
$.each(data.user.playcount, function(i, item) {
html += "<p>" + item.playcount + "</p>";
});
$('#count').append(html);
});
});
The inner foreach loop is unnecessary, user.getInfo returns only one user's information after all. The following should work:
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getInfo&user=XXX&api_key=XXX&format=json", function(data) {
var html = "<p>" + data.user.playcount + "</p>";
$('#count').append(html);
});
});
I have also removed the limit and callback parameters from the URL for brevity.

What is a better way to rewrite this JSON to jQuery data()?

For some reason I have this huge brain fart today. >.<
I have a JSON data that I am attaching to using jQuery .data() that looks like this:
$.getJSON("names.php", function(data) {
//generate html string and append to DOM
$.each(data, function(i,item) {
var strHtml;
strHtml += '<img src="' +item.PIC + '.jpg" id="' + item.ID + '" />';
})
$('body').html(strHtml);
//attach data to image ID
$.each(data, function(i,item) {
$('#' + item.ID).data(item.ID, {
NAME: item.NAME,
PHONE: item.PHONE,
EMAIL: item.EMAIL,
ADDRESS: item.ADDRESS,
...
...
...
});
}
}
This works fine; however, it looks a little ugly and I am trying to clean it up a little mainly on this part:
$.each(data, function(i,item) {
$('#' + item.ID).data(item.ID, {
NAME: item.NAME,
PHONE: item.PHONE,
EMAIL: item.EMAIL,
ADDRESS: item.ADDRESS,
...
...
...
});
}
I am adding an array of object to the key value.
Example from http://api.jquery.com/data/
$('body').data('bar', { myType: 'test', count: 40 });
Here is my attempt to rewrite it:
$.each(data, function(i,item) {
$('#' + item.ID).data(item.ID, function(){
$.each(item) {
return i + ':' item[i];
}
})
}
Is there a cleaner way to write this?
I've also tried $('#' + item.ID).data(item.ID, JSON.stringify(data));
If you just want the full item added, with all it's properties, you can just do this:
$.each(data, function(i,item) {
$('#' + item.ID).data(item.ID, item);
});
.data() takes any value, including an object, so you might as well use the original. Also, it's more likely that you want this:
$.each(data, function(i, item) {
$('#' + item.ID).data("someKey", item);
});
Then you can use a consistent .data("someKey") to get the data back out as well, rather than using the element's own .id as the data key as well.
You can just do:
$('#' + item.ID).data(item.ID, item);
You'll still be able to access the values as expected:
$('#' + someId).data(someId).NAME;
By the way, JSON.stringify isn't a good idea because in order to read the values back again, you'll have to convert it back from a string into an object.
Try:
$('#' + item.ID).data("info", item);

Categories

Resources