I have to display a set of records in a html table. I'm using PHP and jQuery for this.
This is my result set which is retrieved using json_encode()
This is the output of beta.php
[{"StuId":"1","fName":"Saman","lName":"Kumara","age":"14","grade":"A"},{"StuId":"2","fName":"Marry","lName":"Vass","age":"12","grade":"B"},{"StuId":"3","fName":"Navjoth","lName":"Bogal","age":"32","grade":"A"},{"StuId":"4","fName":"Jassu","lName":"Singh","age":"22","grade":"E"}]
I'm using a print.html page as follows to print the above results in a table
$(document).ready(function(){
$getJSON('beta.php' , function(data){
$.each(data, function(){
$.each(this , function(key , value){
$("<table>").appendTo("document.body");
$("<table>").html("<tr><td>" + value.StuId + "</td><td>" + value.fName + "</td><td>" + value.lName + "</td><td>" + value.age + "</td><td>" + value.grade + "</td></tr>");
});
});
});
});
this gives an error saying $getJSON() is not defined
I would be grateful if someone could please help me.
Well when I changed the code as follows I'm able to print the first record in the record set.
But I do not understand why the $.each() wont work????
$("table").html("<tr><td>" + data[0].StuId + "</td><td>" + data[0].fName + "</td><td>" + data[0].lName + "</td><td>" + data[0].age + "</td><td>" + data[0].grade + "</td></tr>");
I tried using a for loop too but then it prints only the last row
$.getJSON('beta.php' , function(data){
$.each(data, function(key, value){
for(var x=0; x < data.length; x++){
$("table").html("<tr><td>" + data[x].StuId + "</td><td>" + data[x].fName + "</td><td>" + data[x].lName + "</td><td>" + data[x].age + "</td><td>" + data[x].grade + "</td></tr>");
$("table").appendTo("document.body");
}
});
})
Can anyone please give your opinion on this :)
$(document).ready(function(){
$.getJSON('beta.php' , function(data){
$.each(data, function(){
$("<table/>").appendTo("document body")
.html("<tr><td>" + this.StuId + "</td><td>" + this.fName + "</td><td>" + this.lName + "</td><td>" + this.age + "</td><td>" + this.grade + "</td></tr>");
});
});
});
In your first example, you appended a new table to the document, and then content to another new table. In your second and third try, you set the content of the first table element present in your document.
Edit: And you iterated too deep, one iteration should suffice.
Try with
$.getJSON("beta.php", function(data) {
var table = $("<table>").appendTo(document.body);
$.each(data, function(i, row) {
var tr = $("<tr>").appendTo(table);
$("<td>").appendTo(tr).html(row.StuId);
$("<td>").appendTo(tr).html(row.fName);
$("<td>").appendTo(tr).html(row.lName);
$("<td>").appendTo(tr).html(row.age);
});
});
Cheers
Related
I'm trying to recieve data in JSON from online php code, I'm getting undefined error
The website i'm retrieving from is https://www.orba.com.ng/getemployees.php
I'm using jQuery
localStorage['serviceURL'] = "https://www.orba.com.ng/";
var serviceURL = localStorage['serviceURL'];
var scroll = new iScroll('wrapper', { vScrollbar: false, hScrollbar:false, hScroll: false });
var employees;
$(window).load(function() {
setTimeout(getEmployeeList, 100);
});
function getEmployeeList() {
$('#busy').show();
$.getJSON(serviceURL + 'getemployees.php', function(data) {
$('#busy').hide();
$('#employeeList li').remove();
employees = JSON.parse(data.items);
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
'<img src="img/' + employee.picture + '" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + ' ' + employee.lastName + '</p>' +
'<p class="line2">' + employee.title + '</p>' +
'<span class="bubble">' + employee.reportCount + '</span></a></li>');
});
setTimeout(function(){
scroll.refresh();
});
});
}
$(document).ajaxError(function(event, request, settings, thrownError) {
$('#busy').hide();
alert("Failed: " + thrownError.error);
});
I'm getting error code undefined
It was a CORS issue, Quite easy to fix. Search on google
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();
EL PROBLEMO
My JSON returns an associative array that I take elements from and display on the page. Sometimes one or more of the sub-arrays will be empty, and this is expected behavior. For those I want nothing displayed on the page. My problem is that currently anytime one of those sub-arrays is empty, I get a "parsererror". In my application, you switch between months, and this AJAX call is made when the dropdown selection is changed to a different month. On months where all the sub-arrays have values, I dont get an error. I only get it when one or more of the sub-arrays are empty.
PHP
first I perform the SQL queries, which I'm leaving out to keep this as short as possible, but these are the 3 resulting arrays:
$income = $results->fetchall(PDO::FETCH_ASSOC);
$expense = $results->fetchall(PDO::FETCH_ASSOC);
$recurring = $results->fetchall(PDO::FETCH_ASSOC);
Then I want to assign those to an array, which I then json_encode:
$array = array(
'income' => $income,
'expense' => $expense,
'recurring' => $recurring
);
echo json_encode($array);
AJAX
This is basically calling the previous php code, then displaying each record from the database in a table.
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
dataType: "JSON",
data: {action: "display_categories", cur_month:cur_month}
});
request.done(function(response){
$('#income tbody tr, #expense tbody tr').remove();
for(var i = 0; i < response.income.length; i++) {
$('<tr><td id="' + response.income[i].cat_id_PK + '">' + response.income[i].cat_name + '</td><td id="' + response.income[i].cat_id_PK +
'">$' + response.income[i].cat_amount + '</td></tr>').appendTo("#income");
}
for(var i = 0; i < response.expense.length; i++) {
$('<tr><td id="' + response.expense[i].cat_id_PK + '">' + response.expense[i].cat_name + '</td><td id="' + response.expense[i].cat_id_PK + '">$' + response.expense[i].cat_amount + '</td></tr>').appendTo("#expense");
}
for(var i = 0; i < response.recurring.length; i++) {
$('<tr><td id="' + response.recurring[i].cat_id_PK + '">' + response.recurring[i].cat_name + '</td><td id="' + response.recurring[i].cat_id_PK + '">$' + response.recurring[i].cat_amount + '</td></tr>').appendTo("#expense");
}
});
request.fail(function(jqxhr, textStatus){
alert("Request failed: " + textStatus);
});
};
JSON
Here's an example JSON response with two empty sub-arrays.
{
"income": [],
"expense": [],
"recurring": [
{
"cat_id_PK": 67,
"cat_name": "Grooming",
"cat_amount": "40.00",
"recur_begin": 1,
"recur_end": 12
}
]
}
Count the number of rows you get from sql query result.
if they are greater than 0 then send an extra field as
$d['status'] ='OK';
if no record exists then send the error handling as
$d['status'] ='ERR';
so check the status field in the data success
dataType: 'json',
data: you data,
success: function( data ) {
if(data.status == "OK"){
alert('success');
} else{
alert('failure');
}
}
});
try like this ,just to test and then use data
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.
Based on several other threads here I think what I'm looking for is json_encode(), though I don't really understand how the output can be used by my JavaScript function. What I'm trying to do is allow users to add additional select lists as needed and have those select options populated from a PHP function that I use to create the initial select list. Here's my JavaScript at the moment:
<script type="text/javascript">
var assigneeCounter = <?php print checkdata("assignee_count", $formvalues, "1"); ?>;
function addInput(fieldlabel, inputclasses, inputCounter, fieldtype = 'input', selectoptions = false){
window[inputCounter]++;
var cleanlabel = fieldlabel.replace(/[^a-zA-Z 0-9]+/g,'');
var cleanlabel = cleanlabel.replace(/\s+/g, '_').toLowerCase();
var newdiv = document.createElement('div');
newdiv.id = cleanlabel + window[inputCounter];
if (fieldtype == 'input') {
newdiv.innerHTML = '<div class="form-item"><label for="' + cleanlabel + '_' + window[inputCounter] + '">' + fieldlabel + ' #' + window[inputCounter] + '</label><input type="text" name="' + cleanlabel + '_' + window[inputCounter] + '" id="' + cleanlabel + '_' + window[inputCounter] + '" value="" class="' + inputclasses + '"><span class="space">Remove</span>';
}
else if (fieldtype == 'select') {
alert(selectoptions);
newdiv.innerHTML = '<div class="form-item"><label for="' + cleanlabel + '_' + window[inputCounter] + '">' + fieldlabel + ' #' + window[inputCounter] + '</label><select name="' + cleanlabel + '_' + window[inputCounter] + '" id="' + cleanlabel + '_' + window[inputCounter] + '" class="' + inputclasses + '">
<span class="space">Remove</span>';
}
document.getElementById(cleanlabel + "_additions").appendChild(newdiv);
document.getElementById(cleanlabel + "_count").value = window[inputCounter];
}
function removeInput(fieldlabel, inputCounter, fieldID){
var element = document.getElementById(fieldlabel + fieldID);
document.getElementById(fieldlabel + "_additions").removeChild(element);
window[inputCounter]--;
document.getElementById(fieldlabel + "_count").value = window[inputCounter];
}
</script>
I'm calling the function in HTML like so:
<div id="assignee_additions"></div>
<p>Add Another Assignee</p>
When I set the value of "fieldtype" to input it works great and creates another input field as expected. The remove function does its job too. But what I really need is a select field, not an input field and that's where my lack of JavaScript knowledge is killing me.
Also, if anyone seems to think that jQuery is a better option here, I'm certainly open to that as well but I don't know that any better than I do traditional JavaScript.
Thanks in advance!
You can create your JSON in a different php file. Then, from your javascript function, you can use an AJAX call to retrieve generated JSON.
I believe you want to json_encode values and keys for <option> tags, right? So, after successful AJAX call, decode your JSON and for each value build a new option.
Rough code in jQuery can look like this:
$.ajax({
url: 'giveMeJSON.php',
dataType: 'json',
success: function(data){
$.each(data.options, function(index){
$('<option>').val($(this).value).text($(this).text).appendTo($('#select_id'));
}
}
})
Read about $.ajax and AJAX.