Write JSON data to HTML5 table - javascript

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.

Related

dynamicly added row cannot run autofill ajax script

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);
});
});

Best way to integrate php and Javascript

I have a .php file where I have some script running to display "cards". I have 6 cards showing and the text being displayed is hard coded. I am ready to start pulling from my database and remove my hard code sections.
//Set number of cards to show
multiplyNode(document.querySelector('.card_content'), 6, true);
var authors = ["Margaret", "Lucy", "Odessa", "Shifty", "Saggy", "Lady"];
var BookNumbers = [2563, 8547, 5896, 4157, 5823, 7963];
$(function(){box_title
//$(".card_content").clone(true).appendTo(".main_card_shell");
$('.box_title').each(function (i) {
$(this).html("<div class='card_name'>" + authors[i] + "</div>" +
"<div class='card_number'>" + BookNumbers[i] + "</div>" +
"<div class='tag_row'>" +
"<div class='sample_tag sample_tag4'></div>" +
"<div class='sample_tag sample_tag3'></div>" +
"</div>");
});
})
I know I can pull the data I want from my database via:
$result = $conn->query("SELECT `Author`, `Book_Num` FROM `Authors`");
but how is the best way to get my $result to replace my hard coded authors and BookNumbers array?
You can loop through the results to build a php array with the same structure as your javascript arrays, then use json_encode to convert it to a javascript array format.
<script type='text/javascript'>
<?php
$result = $conn->query("SELECT `Author`, `Book_Num` FROM `Authors`");
// loop through the results to build the php arrays
while($row = $result->fetch_array())
{
// set the author and book number to array with numeric key
$authors[] = $row['Author'];
$BookNumbers[] = $row['Book_Num'];
}
// use json_encode to convert the php array to an javascript array
echo "var authors = ".json_encode($authors).";\n";
echo "var BookNumbers = ".json_encode($BookNumbers).";\n";
?>
</script>
A comment: unless you need interactivity you could build the html with php without using jquery

Trying to set up mailto: link

I have a webpage that has a form to insert vendor data, once inserted the company name is the placed into a select box. when the company is selected a table is called with all the vendor information.
My problem is the
the vendor_email is called from a php script, is there a way to make the value of the id insert into a mailto: function.
<tbody id="records">
<td id="vendor_company"></td>
<td id="vendor_rep"></td>
<td id="vendor_email"></td>
</tbody>
<div class="row" id="no_records"><div class="col-sm-4">Plese select vendor name to view details</div></div>
here is my php and js code
<?php
include_once("Database/db_connect.php");
if($_REQUEST['empid']) {
$sql = "SELECT id, companyName, repName, venderEmail FROM vender_contact
WHERE id='".$_REQUEST['empid']."'";
$resultset = mysqli_query($conn, $sql) or die("database error:".
mysqli_error($conn));
$data = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
$data = $rows;
}
echo json_encode($data);
} else {
echo 0;
}
?>
my js code
$(document).ready(function(){
// code to get all records from table via select box
$("#vendors_data").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'empid='+ id;
$.ajax({
url:"getVendor.php",
dataType: "json",
data: dataString,
cache: false,
success: function(vendorData) {
if(vendorData) {
$("#heading").show();
$("#no_records").hide();
$("#vendor_company").text(vendorData.companyName);
$("#vendor_rep").text(vendorData.repName);
$("#vendor_email").text(vendorData.venderEmail);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
})
});
It's absolutely possible! You simply need to use .html() instead of .text().
Note that the mailto comes on the href attribute, which is unique to the <a> tag. As such, you'll want to place your inside of your <td id="vendor_email"></td>:
$("#vendor_email").html("<a href='mailto:" + vendorData.vendorEmail + "'>" + vendorData.vendorEmail + "</a>");
Which will render as something like:
vendorData = {};
vendorData.vendorEmail = 'test#test.com';
$("#vendor_email").html("<a href='mailto:" + vendorData.vendorEmail + "'>" + vendorData.vendorEmail + "</a>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="vendor_email"></div>
In addition to this, please be aware that your MySQLi is vulnerable to SQL injection. You should use prepared statements, and also ensure that your database user only has the required privileges in order to prevent this.
You can refer to this post for further information on how to prevent SQL injection in PHP :)
Hope this helps!
By using jQuery's .html() method you can insert html like so:
$( '#vendor_email' ).html( '' + vendorData.vendorEmail + '' );
By the way, I couldn't help but notice that you've spelled vendor as "vender" in venderEmail.

Pagination of table data from json

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

Getting data-fields from td:first row

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()

Categories