I'm following through an example which deals with the following json object passed from a php page:-
{"book":[{"title":"Harry Potter","author":"J K. Rowling","year":"2005","price":"29.99"},{"title":"Learning XML","author":"Erik T. Ray","year":"2003","price":"39.95"}]}
I know that you can iterate through and print all the data to a table as follows:
$.each(data.book, function(index, book) {
content = '<tr><td>' + book.title + '</td>';
content += '<td>' + book.author + '</td>';
content += '<td>' + book.year + '</td>';
content += '<td>' + book.price + '</td></tr>';
$(content).appendTo("#content2");
});
But say the json data is dynamic following the same structure, how can I adapt the above code to work for this? I was thinking I would need some sort of nested loop.
Whats causing me confusion is that for the line $.each(data.book, function(index, book) {
data.book will not always be data.book they would be data.foo
and the lines which refer to book.title will not always be the same it could be book.bar
Any guidance most appreciated
Yes you can do it in a nested loop like this
var content = '';
$.each(data.book, function(index, book) {
content += '<tr>';
$.each(book,function(k,v){
content += '<td>' + v + '</td>';
});
content += '</tr>';
});
$(content).appendTo("#content2");
http://jsfiddle.net/tjjQh/
Oh.. then use the for in loop
for (v in data) {
$.each(data[v], function(index, book) {
content += '<tr>';
$.each(book, function(k, v) {
content += '<td>' + v + '</td>';
});
content += '</tr>';
});
}
http://jsfiddle.net/8YCgA/
You may want to check out jQuery Templating.
var data = [
{ name : "John", age : 25 },
{ name : "Jane", age : 49 },
{ name : "Jim", age : 31 },
{ name : "Julie", age : 39 },
{ name : "Joe", age : 19 },
{ name : "Jack", age : 48 }
Can be expressed as:
<li>
<span>{%= $i + 1 %}</span>
<p><strong>Name: </strong> {%= name %}</p>
{% if ($context.options.showAge) { %}
<p><strong>Age: </strong> {%= age %}</p>
{% } %}
</li>
Related
I have a Jquery function that is using getJson. I am trying to form something like www.mysite.com/?state=oregon. According to Jquery ("Data that is sent to the server is appended to the URL as a query string..."), but I get all the values in the json data. What I am doing wrong.
Here is my code
function changeLine(line){
$('#table_lines').html('');
$.getJSON("../index.php", {, line}, function(data){
var line_data = '';
$.each(data, function(key, value){
line_data += '<tr id="' +value.line_id+'">';
line_data += '<td>' + otherValueTime(value.MatchTime)+'</td>';
line_data += '<td>' + value.home+'</td>';
line_data += '<td>' + value.away+'</td>';
for(i=0; i < value.Cases.length; i++){
console.log(value.Cases[i].CaseType + ' ' + value.Cases[i].CaseAway + ' ' + value.Cases[i].CaseHome);
if(value.Cases[i].CaseType === "Game"){
line_data += '<td>' + value.Cases[i].CaseAway +'</td>';
line_data += '<td>' + value.Cases[i].Total +'</td>';
line_data += '<td>' + value.Cases[i].Over +'</td>';
}
}
});
$('#table_lines').append(line_data);
});
}
On the line with this code "{, line}", I tried putting the key value from the json array, like {id: line}. What I want to do is to get a group of cases according to the key.
I would like to know how you do that. I want to change it according to the option value. I do get data from the server, but I get all the data. Here is how I call that function
$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str = $( this ).val();
$.ajax({
method: "POST",
url: "../index.php",
data: { 'id' : str }
})
});
changeLinea(str);
})
.change();
In an ajax call, i need to obtain, as a response, the value of a parameter of a JSON object, but i don't understand how to do it.
If this is my PHP file in which i reproduce the JSON structure
echo " { ";
echo '"general" : {';
echo '"obj" : [
{"name" : "Primo", "description" : "Descrizione associata alla prima voce"},
{"name" : "Secondo", "description" : "Descrizione associata alla seconda voce"},
{"name" : "Terzo", "description" : "Descrizione associata alla terza voce"}
]}}';
And this is my HTML file
$(document).ready(function(e) {
$('#name li').click(function() {
var name = $(this).text();
url = "example.php?name=" + name;
$.getJSON(url,
function(json) {
//for (i = 0; i < json.general.obj.length; i++) {
//output = "<tr>";
output = "<td>" + json.general.obj[0].name + "</td>";
output += "<td>" + json.general.obj[0].description + "</td>";
//output += "</tr><br/>";
console.log(output);
$("#response").append(output);
//}
});
});
});
<ul id="name">
<li data-id="1">Primo</li>
<li data-id="2">Secondo</li>
<li data-id="3">Terzo</li>
</ul>
<div id="response">
<!--Data goes here-->
</div>
Which is the right way to go? Where do i need to place the $_REQUEST['name'] variable to receive back as a response the desired "Description" value?
I'm stuck there
You can use the data-id to retrieve the specific item of the array by its index, something like this:
$('#name li').click(function() {
var name = $(this).text();
var index = $(this).data('id') -1;
var url = "example.php?name=" + name;
$.getJSON(url, function(json) {
output = "<p>" + json.general.obj[index].name + "</p>";
output += "<p>" + json.general.obj[index].description + "</p>";
$("#response").append(output);
});
});
Example fiddle
Note that I changed td in the output to p as td elements are only valid within tables.
Also, if you only want the data of the last clicked element to be visible (instead of appending a new set each time) you can use:
$("#response").html(output);
This is a .php file that creates a table.
<table id="contact-messages">
<thead>
<tr>
<th>Username</th><th>Category</th><th>Message</th><th>Created at</th>
</tr>
</thead>
<tbody>
<?php
foreach ($contact_messages as $message) {
echo '<tr>'
. '<td>' . htmlentities($message['username']) . '</td>'
. '<td>' . htmlentities(ucfirst($message['category'])) . '</td>'
. '<td>' . nl2br(htmlentities($message['message'])) . '</td>'
. '<td class="created-at" data-created_at="' . htmlentities($message['created_at']) . '"></td>'
. '</tr>';
}
?>
</tbody>
</table>
And this is the .js file for that page. This code changes the content of the table.
$.get("contact-messages.php", { "category": category }, function (data) {
$("#contact-messages").find("tbody").empty(); // Empty the old messages.
for (var i = 0; i < data.length; i++) {
$("#contact-messages").find("tbody")
.append(($("<tr/>")
.append($("<td/>", { text: ((data[i].username === null) ? '' : data[i].username) }))
.append($("<td/>", { text: data[i].category }))
.append($("<td/>", { text: data[i].message }))
.append($("<td/>", {
text: data[i].created_at,
class: 'created-at',
'data-created_at': data[i].created_at
}))
));
}
}, 'json');
So, every time that I want to change the structure of the table I have to change the .php and .js files.
Now, the questions is, Is there any way to store the structure of the table in one file and every times that I want to change the structure, I just change that file?
Create all html in php page and call this php page using $.ajax request and finally use response coming from the ajax request with appropriate method $("#contact-messages").html(reponse) / $("#contact-messages").append(response) / $("#contact-messages").prepend(response).
You can use only ajax as #jQuery Angry Bird said and you should note that it would be better if you do call .append() or .html() just once and not in a loop (to reduce the execution time a little bit)
$.get("contact-messages.php", { "category": category }, function (data) {
$("#contact-messages").find("tbody").empty(); // Empty the old messages.
var tmpStr = '';
for (var i = 0; i < data.length; i++) {
tmpStr = '';
tmpStr+='<tr>';
tmpStr+='<td>'+(data[i].username === null) ? '' : data[i].username)+'<td/>';
tmpStr+='<td>'+data[i].category+'</td>'
tmpStr+='<td>'+data[i].message+'<td>'
tmpStr+='<td class="+created-at+" data-created_at="++">'+data[i].created_at+'</td>'
tmpStr+='</tr>';
}
//call .html() once instead of .append() data.length*5 times
$("#contact-messages").find("tbody").html(tmpStr);
}, 'json');
I am using jQuery (1.9.1) with jQuery Mobile (1.3.0). I am having trouble with the Reflow table in JQM. When I AJAX to get my JSON data from a script to add more rows to my table, the reflow table headings are not generated after I trigger a refresh and create on the table. Here is my code:
HTML/PHP
'<table data-role="table" id="itemTable" data-mode="reflow" class="ui-responsive table-stroke" style="display:table;">' .
'<thead>' .
'<tr>' .
'<th data-priority="1">Location</th>' .
'<th>Name</th>' .
'<th data-priority="3">Barcode</th>' .
'<th data-priority="4">Needed</th>' .
'<th data-priority="5">Scanned</th>' .
'</tr>' .
'</thead>' .
'<tbody>' .
$tableData .
'</tbody>' .
'</table>' .
JavaScript
$('.getOrder, .getStoreOrder').on('vclick', function(e) {
e.preventDefault();
var sel = this;
var theLink = $(this).attr('href');
if (activeOrder === true) {
return false;
}
$.ajax({
url: 'ajax.php',
data: {
pa: ($(sel).hasClass('getStoreOrder') ? 'store' : '') + 'order'
},
dataType: 'json',
beforeSend: function() {
$.mobile.showPageLoadingMsg();
$('#itemTable tbody').html('');
$('#leftPanel ul li').not(':first-child').remove();
},
success: function(data) {
testVar = data;
var i;
for (i=0; i <= data.length -1; i++) {
$('#itemTable tbody').append( '' +
'<tr id="item' + (i+1) + '">' +
'<td><span>' + data[i].Location + '</span></td>' +
'<td><a onclick="showImageOverlay(\'' + data[i].Image + '\');">' + data[i].Name + '</a></td>' +
'<td>' + data[i].Barcode + '</td>' +
'<td>' + data[i].Qty + '</td>' +
'<td>0</td>' +
'</tr>' +
'');
$('#leftPanel ul').append( '' +
'<li>' +
'<a href="#item' + (i+1) + '" class="itemLink" onclick="changeItem(\'item' + (i+1) + '\')">' +
'Item ' + (i+1) +
'</a>' +
'</li>' +
'');
}
$('#itemTable').trigger('refresh');
$('#itemTable').trigger('create');
$('#leftPanel #leftUl').listview('refresh');
},
complete: function() {
$('#rightPanel', '.ui-page-active').panel('close');
$.mobile.hidePageLoadingMsg();
//pageChange(theLink);
}
});
});
The AJAX does succeed and add my rows to the table how I want them to. My question is how do I trigger JQM to add the reflow column names.
I know that I can use <b class="ui-table-cell-label">Column Name</b> to my row appends to add the column names but I want it done dynamically so I don't have to change the jQuery when I change my HTML.
Thank you.
In my opinion its preferable to do like this: $('#tableContainer').load('revisedTable.php?json=yourJsonString');
That way you're doing the table layout in php rather than javascript.
Figured it out. Turns out that jQuery Mobile version 1.3.0 does not have a proper .table('refresh') method implemented. I solved this by upgrading to jQuery Mobile version 1.3.1 which has the proper method I needed.
I have created HTML TABLE from JSON data of PHP using JQuery.
After creating table, I try to attach table sorter (JQuery)
but, it doesn't work. How to solve? Code below:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON('listnotice.php', function(data) {
var table = "";
$.each(data, function(index,entry) {
table += '<tr>';
table += '<td>' +entry["title"] + '</td>';
table += '<td>' +entry["content"] + '</td>';
table += '<td>' +entry["date"] + '</td>';
table += '</tr>';
});
table += "</tbody>";
$("#noticeList").append(table);
});
$("#noticeList").tablesorter({debug: false, widgets: ['zebra'], sortList: [[0,0]]}).tablesorterFilter({filterContainer: $("#filter-box"),
filterClearContainer: $("#filter-clear-button"),
filterColumns: [0],
filterCaseSensitive: false});
});
</script>
</head>
<body>
<table id="noticeList">
<thead><tr><th>1</th><th>2</th><th>3</th></tr></thead><tbody>
</tablev>
</body>
</html>
You need to apply the tablesorter in the same callback where you are building the table. The getJSON call is asynchronous and the way you have it now, you're applying tablesorter before the call returns and the table is built.
$.getJSON('listnotice.php', function(data) {
var table = "";
$.each(data, function(index,entry) {
table += '<tr>';
table += '<td>' +entry["title"] + '</td>';
table += '<td>' +entry["content"] + '</td>';
table += '<td>' +entry["date"] + '</td>';
table += '</tr>';
});
table += "</tbody>";
$("#noticeList").append(table)
.tablesorter({debug: false, widgets: ['zebra'], sortList [[0,0]]}).tablesorterFilter({filterContainer: $("#filter-box"),
filterClearContainer: $("#filter-clear-button"),
filterColumns: [0],
filterCaseSensitive: false});
});
The ajax request would still be executing as the .tablesorter() plugin is called. If you move the table sorter inside your success handler, it should work.
Try this:
$(document).ready(function() {
$.getJSON('listnotice.php',
function(data) {
var table = "";
$.each(data, function(index,entry) {
table += '<tr>';
table += '<td>' +entry["title"] + '</td>';
table += '<td>' +entry["content"] + '</td>';
table += '<td>' +entry["date"] + '</td>';
table += '</tr>';
});
table += "</tbody>";
$("#noticeList").append(table).tablesorter({debug: false, widgets: ['zebra'], sortList: [[0,0]]}).tablesorterFilter({filterContainer: $("#filter-box"),
filterClearContainer: $("#filter-clear-button"),
filterColumns: [0],
filterCaseSensitive: false});
}
);
});