I want to paginate results obtained thusly:
function processResponse(response){
var myObj = JSON.parse(response);
var weighInData = myObj["WEIGH-INS"];
var weights = []; // re: weigh-in count and calculating highest/lowest
var userDisplayEl1 = document.getElementById("user-display-weigh-in-data");
var weighInCountEl = document.getElementById("weigh-in-count");
var weightLowEl = document.getElementById("weight-low");
var weightHighEl = document.getElementById("weight-high");
var weightgoalEl = document.getElementById("weight-goal");
var dataRows = document.getElementById("data-rows");
userDisplayEl1.innerHTML = "";
weighInCountEl.innerHTML = "";
weightLowEl.innerHTML = "";
weightHighEl.innerHTML = "";
weightgoalEl.innerHTML = "";
dataRows.innerHTML = "";
for (var obj in weighInData) {
if (weighInData[obj].user === selUser) {
weights.push(weighInData[obj].weight);
var row = "<tr>" +
"<td class=\"date\">" + weighInData[obj].date + " </td>" +
"<td class=\"value\">" + weighInData[obj].weight + "</td>" +
"</tr>";
dataRows.innerHTML += row;
// pagination here?
} // if ... === selUser
} // for var obj in weighInData
var weighInCount = weights.length;
var weightLowest = Math.min.apply(null, weights);
var weightHighest = Math.max.apply(null, weights);
userDisplayEl1.innerHTML = weighInData[obj].user + "'s weigh-ins:";
weightLowEl.innerHTML += weightLowest;
weightHighEl.innerHTML += weightHighest;
weighInCountEl.innerHTML = weighInCount;
} // processResponse
It seems that, because I'm executing Math on the results (after the for loop), I cannot use a limit in my db query, else the math would be inaccurate (executing only on the chunks of data, and not on the entirety of the data). So it seems I'll have to paginate on the client, but I have no idea how to proceed given how I'm currently loading/displaying the data. I have looked briefly at a couple of pagination plugins but since I wasn't clear on how to implement them given my extant code, I prefer the learning curve of achieving this w/out a plugin (or jQuery).
Any suggestions/pushes in the right direction, with the assumption that I con't substantively alter what I have now (which works, and which I understand, will be most appreciated.
Btw, my server-side code, fwiw:
$table = "`WEIGH_IN_DATA`";
if ($mysqli) {
$user = $_GET['selUser'];
$i = 0;
$jsonData = '{"WEIGH-INS": [';
$stmt = $mysqli->stmt_init();
$query = "SELECT * FROM $table WHERE USER = '$user'";
$result = $mysqli->query($query) or die("Error in the query (?)" . mysqli_error($mysqli));
while($row = mysqli_fetch_array($result)) {
$i++;
$user = $row["USER"];
$date = $row["DATE"];
$weight = $row["WEIGHT"];
$jsonData .= '{"user": "'.$user.'", "date": "'.$date.'", "weight": "'.$weight.'" },';
}
$jsonData = chop($jsonData, ","); // kill the trailing comma
$jsonData .=']}';
echo $jsonData;
}
Thank you,
svs
To save time, using a plug-in might be your best bet. I'm sure there are tutorials on building your own pagination plug-in on the internet which you can google.
I picked a random jQuery pagination plug-in (datatables), appended some data via js (similar to your code), then called the plug-in on the result table. Something like this may/may not work for you. Also, this is dependent on jQuery, and I'm not sure if you can include this library or not on your website.
Here's an example using dataset and jquery: http://codepen.io/anon/pen/IbBxf
Link to datatables: http://www.datatables.net/
$(document).ready(function(){
// append some data to an existing table in the DOM
for (var i =0 ; i < 10; i++) {
var $nr = $('<tr><td>A-' + i + '</td><td>B-' + i + '</td></tr>');
$('#myTable').append($nr);
}
// after table is populated, initiate plug-in and point to table
$('#myTable').DataTable(
{ "lengthMenu": [[5, 10, -1], [5, 10, "All"]] });
});
If you can't use jQuery:
Vanilla JS: It looks like this library can do pagination, however you'll need to read through the docs:
http://listjs.com/docs/plugins/pagination
This link also looks promising for your case (vanilla JS only):
http://www.tekgarner.com/simple-pagination-using-javascript/
HTML/CSS: If you don't need a lot of features, maybe you could also look at just adding a scrollbar to your HTML table results.
How to display scroll bar onto a html table
Related
i am new to programming. so i want to make a table that user can add new rows by clicking a button.
and in that rows, user can input one fields (ID) with some registered series of numbers and then the other fields (parts name) shows the part's name according my other table.
I managed to create a code that works on adding new rows and autofill via ajax.
but unfortunately, the autofill only works on top/first row. but when i input ID on second or third row, the parts name's field did not show up.
what am i missing? this is my add row code:
<script>
var no = 0;
function addItem() {
no++;
var html = "<tr>";
html += "<td>" + no + "</td>";
html += "<td><input type='text' name='id_sap[]' onkeyup='autofills()' id='sappart' required></td>";
html += "<td><input type='text' name='material_name[]' id='namapart' required></td>";
html += "<td><input type='number' name='outcoming_qty[]' required /></td>";
html += "<td><button type='button' onclick='deleteRow(this);'>Delete</button></td>"
html += "</tr>";
var row = document.getElementById("tbody").insertRow();
row.innerHTML = html;
}
function deleteRow(button) {
button.parentElement.parentElement.remove();
// first parentElement will be td and second will be tr.
</script>
and this is my autofill code:
<script type="text/javascript">
function autofills(){
var parts = $('input[name="id_sap[]"]').val();
var sloc = $('input[name="tarea"]').val();
$.ajax({
url: 'ajax1.php',
data: {"id_sap":parts,"storage_location":sloc},
}).success(function (data) {
var json = data,
obj = JSON.parse(json);
$('input[name="material_name[]"]').val(obj.material_name);
});
}
</script>
and this is my ajax page:
<?php
//membuat koneksi ke database
$koneksi = mysqli_connect("localhost", "shaun", "godbless19", "dboptima");
//variabel nim yang dikirimkan form.php
$nomorsap = $_GET['id_sap'];
$areas = $_GET['storage_location'];
//mengambil data
$query = mysqli_query($koneksi, "SELECT * FROM material_card where id_sap = '$nomorsap' and storage_location = '$areas'");
$spare = mysqli_fetch_array($query);
$data = array(
'material_name' => $spare['material_name']);
//tampil data
echo json_encode($data);
?>
please help me , i have been wasting too much effort and time to solve this
so far i keep looking similar issues on stack overflow, none of them seems to work.
thank you very much
best regards
Try the following:
$(document).on('keyup', "#sappart input[type='text']", function() {
var parts = $('input[name="id_sap[]"]').val();
var sloc = $('input[name="tarea"]').val();
$.ajax({
url: 'ajax1.php',
data: {
"id_sap": parts,
"storage_location": sloc
},
}).success(function(data) {
var json = data,
obj = JSON.parse(json);
$('input[name="material_name[]"]').val(obj.material_name);
});
});
Currently when asking the server for data, when one single set is sent back like so
{"num":1,"notification_id":"818","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
the div is inserted.
But lets say there's two sets with different notification id's like so
{"num":1,"notification_id":"818","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
{"num":1,"notification_id":"819","notification_content":
"Lucy Botham posted a status on your wall","notification_throughurl"}
Nothing happens
So I'll cut the code down as to show and example of what I have
success: function(response){
if(response.notification_id > notification_id){
$("#notif_ui"+ notification_id).prepend('
<div class="notif_text"><div id="notif_actual_text-'+response['notification_id']+'"
class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped'+response
['notification_triggeredby']+'.jpg\"
onerror=this.src=\"userimages/no_profile_img.jpeg\"
width=\"40\" height=\"40\" ><br /></div></div>');
i = parseInt($("#mes").text()); $("#mes").text((i+response.num));
}
I was toying with the idea of maybe using
$.each(response, function (i, val)
But I'm still unsure.
EDIT
Exact response how it shows
{"num":1,"notification_id":"823","notification_content":"Lucy Botham posted a status on your wall","notification_throughurl"
:"singlepoststreamitem.php?streamitem_id=703","notification_triggeredby":"85","notification_status":"1"
,"notification_time":"2015-11-08 04:16:26"}{"num":1,"notification_id":"824","notification_content":"Lucy
Botham posted a status on your wall","notification_throughurl":"singlepoststreamitem.php?streamitem_id
=704","notification_triggeredby":"85","notification_status":"1","notification_time":"2015-11-08 04:16
:27"}
AND MY WHILE LOOP
while($row = mysqli_fetch_assoc($com)){
if($row['notification_status']==1){
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json['notification_id'] = $row['notification_id'];
$json['notification_content'] = $row['notification_content'];
$json['notification_throughurl'] = $row['notification_throughurl'];
$json['notification_triggeredby'] = $row['notification_triggeredby'];
$json['notification_status'] = $row['notification_status'];
$json['notification_time'] = $row['notification_time'];
echo json_encode($json);
}}
First you need to build an array of notifications, rather than a single one:
<?php
$json = array(
'notifications' => array()
);
while ($row = mysqli_fetch_assoc($com)) {
if ($row['notification_status'] == 1) {
$num = mysqli_num_rows($com);
$notification = array();
if ($num) {
$notification['num'] = 1;
} else {
$notification['num'] = 0;
}
$notification['notification_id'] = $row['notification_id'];
$notification['notification_content'] = $row['notification_content'];
$notification['notification_throughurl'] = $row['notification_throughurl'];
$notification['notification_triggeredby'] = $row['notification_triggeredby'];
$notification['notification_status'] = $row['notification_status'];
$notification['notification_time'] = $row['notification_time'];
$json['notifications'][] = $notification;
}
}
echo json_encode($json);
?>
Then you can access the notifications array from JavaScript:
success: function(response) {
$.each(response.notifications, function(i, notification) {
if (notification.notification_id > notification_id) {
$("#notif_ui" + notification_id).prepend('<div class="notif_text"><div id="notif_actual_text-' + notification['notification_id'] + '" class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped' + notification['notification_triggeredby'] + '.jpg\" onerror=this.src=\"userimages/no_profile_img.jpeg\" width=\"40\" height=\"40\" ><br /></div></div>');
i = parseInt($("#mes").text());
$("#mes").text((i + response.num));
}
})
}
Note, completely untested, but hopefully you can see the difference!
Your php could be changed to
// you can just the the number of rows once outside the while loop
$num = mysqli_num_rows($com);
if($num){
$jsonNum = 1;
}else{
$jsonNum = 0;
}
while($row = mysqli_fetch_assoc($com)){
if($row['notification_status']==1){ // this would be unnecessary if you add it as a where conditional to your sql query
// add the num to the array to match your current data structure
$row['num'] = $jsonNum;
$json[] = $row;
}
}
echo json_encode($json);
I've got the following snippet of code:
function getData(){
$.get('http://mywebsite.net/getFile.php', function(data) {
var result = JSON.parse(data);
}
That returns the following JSON data:
Object {0: "11", 1: "MobileAppBackUp150715", 2: "rob#gmail.com", FileID: "11", FileName: "MobileAppBackUp150715", FileEmail: "rob#gmail.com"}
I've two issues:
First of all my JSON data is incorrect, there should be more than one object returned. Here is how I'm creating my JSON data:
$result = mysql_query("SELECT FileID, FileName, FileEmail FROM tblfiles WHERE FileEmail = '".$email."'");
$row = mysql_fetch_array($result);
if($row['FileEmail'] == $email) {
echo json_encode($row);
}
In the table tblfiles there are 2 rows of data I know for definite.
My second issue is I'm not sure how to go about writing my JSON results into a html table.
EDIT: UPDATE:
using the following php script I've managed to output the 2 rows that I know exist in my table:
$result = mysql_query("SELECT FileID, FileName, FileEmail FROM tblfiles WHERE FileEmail = '".$email."'");
$row = array();
if(mysql_num_rows($result) > 0) {
while($r = mysql_fetch_assoc($result)) {
$id = $r["FileID"];
$row[$id] = $r;
}
}
echo json_encode($row);
That produces the following:
{"11":{"FileID":"11","FileName":"MobileAppBackUp150715","FileEmail":"rob#gmail.com"},"14":{"FileID":"14","FileName":"MyFile","FileEmail":"rob#gmail.com"}}
Now I need to use JS to get into a table in a HTML page
Or, to do everything in a single command in your callback function, you could do
$('#target').html('<table>'+$.map(result,function(d){return '<tr><td>'+$.map(d,function(e){return e;}).join('</td><td>')+'</td></tr>'}).join('\n')+'</table>');
Where #target is the id of a div where you want the table to be and result is the object you got from your $.get() call. I have not done the headings yet but that should be easy for you to fix.
var result={"11":{"FileID":"11","FileName":"MobileAppBackUp150715","FileEmail":"rob#gmail.com"},"14":{"FileID":"14","FileName":"MyFile","FileEmail":"rob#gmail.com"}};
$('#target').html('<table>'+$.map(result,function(d){return '<tr><td>'+$.map(d,function(e){return e;}).join('</td><td>')+'</td></tr>'}).join('\n')+'</table>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target"></div>
I'm going to use jquery to answer you. You can easily add jquery to your project.
var $row = "<tr><td>" + result[0] + "</td><td>" + result[1] + "</td></tr>";
var $table = $("table"); //selects your table
$table.append(row);
That's a way to do it. It is simple but probably not the best. I can recommend looking into some plugin such as knockout.js if you need to populate a lot of html based on json
hope it helps!
On the back of the accepted answer above I'd like to share the code that is working for me.
There is no need to use JSON.parse() as using getJSON() function already returns the JSON data as on object.
<script>
$.getJSON('http://safe.net/getFile.php', function(json) {
var tr;
for(var i in json)
{
tr = $('<tr>');
tr.append("<td>" + json[i].FileName + "</td>");
tr.append("<td>" + json[i].FileID + "</td>");
tr.append("<td>" + json[i].FileEmail + "</td>");
$('table').append(tr);
console.log(json[i].FileName);
}
//console.log(json);
});
</script>
Thanks to cars10 above for the help.
I'm attempting to use DataTables Server Side Processing
Currently I'm getting 1000 rows back (as display) even though the display is set to 10, 25, etc
jQuery:
$(document).ready(function() {
$('#paginatedTableSS').dataTable( {
"processing": true,
"serverSide": true,
"ajax": "script.php"
} );
} );
script.php:
$i = 0;
$test = array();
$test['draw'] = 1;
$test['recordsTotal'] = 200000;
$test['recordsFiltered'] = 8;
$test['data'] = array();
while($i<=20){
array_push($test['data'], ['test1 ' . $i, 'test2 ' . $i, 'test3 ' . $i, 'test4 ' . $i]);
$i=$i+1;
}
echo json_encode($test);
My ultimate goal is to pass along start to the script so the script can use that to give the correct data back. But currently I need to fix the above before moving forward I think. But I'm not sure what's wrong with it or how to debug it.
aaData seems to indicate that you're using the legacy datatables. If that's the case, you're missing iTotalRecords, iTotalDisplayRecords and sEcho.
$test['iTotalRecords'] = count($test['aaData']);
$test['iTotalDisplayRecords'] = count($test['aaData']);
$test['Echo'] = $_REQUEST['sEcho'];
see http://legacy.datatables.net/usage/server-side
if you're not using the legacy datatables you need to use data, records and recordsFiltered instead (as referenced in your link)
Edit
The reason your table is displaying 1000 rows is because that's the # of rows you're returning. Use the length and start parameters to determine which rows to return i.e
$start = (isset($_REQUEST['start']) && is_numeric($_REQUEST['start']))
? $_REQUEST['start'] : 0;
$length = (isset($_REQUEST['length']) && is_numeric($_REQUEST['length']))
? $_REQUEST['length'] : 100;
$test = array('data'=>array(), 'recordsTotal', 'draw', 'recordsFiltered');
for($i=$start; $i<=$length; $i++) {
array_push($test['data'], array('id'=>$i,'date'=>$i,'status'=>$i,'options'=>$i));
}
$test['recordsTotal'] = 200000;
$test['draw'] = 1;
$test['recordsFiltered'] = count($test['data']);
echo json_encode($test);
I have a table that gets created using php drawing straight out of a database. Each td is editable and, when the mouse is clicked elsewhere, the new data is sent to the database and updated dynamically through .ajax(). That all works flawless. It does so through the data-fields of each td. They correspond with the field name in the database so the query has the proper WHERE clause.
Now, I have an ADD button that creates a new row of data that is also editable and can be edited and saved in the same manner. Currently I can add a row. I am trying to create an array of the data-fields from the first row of td so I can then add those to the newly created td during their creation loop. I am only able to get the data-field of the first and/or second td, though, not the entire row as I am intending. How, given the code I have, can I do that? Is it even possible with the configuration that I have? Thanks.
<script type="text/javascript">
/* Add a new table row to the bottom of the table */
$(document).ready(function() {
$(".add").click(function() {
$("#table").each(function() {
//create array
/* $('.edit_tr:last').find('.edit_td').each(function() {
var fieldArray = [];
fieldArray.push($('.edit_tr:last').find('.edit_td').attr('data-field'));
}); */
var fieldArray = [];
// fieldArray.push($('.edit_tr:last').find('.edit_td').last().attr('data-field'));
var $table = $(this);
// var field = $('.edit_tr').find('td:last').attr('data-field');
var id=$('#table tr:last').attr('id');
var $tr = $("#table").children('tr');
// var $th = $(this).closest('table').find('th').eq($(this).index());
// Number of td's in the last table row
var n = $('tr:last td', this).length;
var tds = '<tr class="edit_tr" id="' + id++ + '">';
// array
currentDataField = $('.edit_tr:first').find('.edit_td').first().attr('data-field');
console.log(currentDataField);
for (var i = 0; i < n; i++) {
fieldArray.push(currentDataField);
currentDataField = $('.edit_tr:first').find('.edit_td [data-field=' + currentDataField + ']').next().attr('data-field');
// currentDataField = $('.edit_tr').find('.edit_td').nextAll().attr('data-field');
}
console.log('fieldArray ' + fieldArray);
// console.log(field);
for (var i = 0; i < n; i++) {
tds += '<td class="edit_td"><input type="text" class="editbox" id="' +
id + '" data-field="' + fieldArray[i] + '"/> </td>';
console.log('fieldArray loop ' + fieldArray[i]);
}
tds += '</tr>';
// console.log(tds);
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
}
else {
$(this).append(tds);
}
});
});
});
</script>
PHP code for table creation:
public function displayTable($table)
{
//connect to DB
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo "<table id='table' border='1'>"; //start an HTML table
$dbtable = $table;
$fields =array();
$result = mysqli_query($con, "SHOW COLUMNS FROM ".$dbtable);
//fill fields array with fields from table in database
while ($x = mysqli_fetch_assoc($result))
{
$fields[] = $x['Field'];
}
$fieldsnum = count($fields); //number of fields in array
//create table header from dbtable fields
foreach ($fields as $f)
{
echo "<th>".$f."</th>";
}
//create table rows from dbtable rows
$result = mysqli_query($con, "SELECT * FROM ".$dbtable);
while ($row = mysqli_fetch_array($result))
{
$rowid = $row[$fields[0]];
echo "<tr class='edit_tr' id='".$rowid."'>";
foreach ($fields as $f)
{
echo "<td class='edit_td' data-field='".$f."'><span id='".$rowid."' class='text'>".$row[$f]."</span>
<input type='text' value='".$row[$f]."' class='editbox' id='".$rowid."' data-field='".$f."'/> </td>";
}
$rowid++;
echo "</tr>";
}
echo "</table>"; //close the HTML table
$recordid = $rowid;
//close connection
mysqli_close($con);
}
Okay, there's a lot of code in there (and I'm not a PHP user, so I had to give it my best shot at testing out on some sample HTML :D ), so here's what I think will get you past the issue that you are having with the data-field values, but I'll stop there:
<script type="text/javascript">
$(document).ready(function() {
/* Add a new table row to the bottom of the table */
$(".add").click(function() {
var fieldArray = [];
var $table = $("#table");
var $lastRow = $table.find("tr:last");
var $dataFields = $lastRow.find("td");
$dataFields.each(function() {
fieldArray.push($(this).attr("data-field"));
});
. . . .
That should get you your fieldArray value, populated with the data-field values from all of the td elements in the last row of the table.
A couple of side notes:
again, my PHP isn't great, but it doesn't look like you are creating your th values inside a row in the table . . . they really should be wrapped in a tr element
you could get the $dataFields value in one line of code (several ways, actually), but splitting it up into three lines, like I did, is actually faster (and a little easier to read, in my opinion :) ).
If you set data attributes via jQuery function .data(), then these attributes are hidden attributes and cannot be found from $('.item [data-...]').
if you need to set string or number to data attribute, then set it with .attr('data-NAME', value) function
You can find all elements without searching data attribute and then filter elements with function jQuery.map()