how to convert my result in table format - php

I am trying post my json result in table format how should achieve that.Igot result as
I want it to display in table format .Here is my code
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"> </script>
</head>
<body>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'example.php',
data: "",
dataType: 'json',
success: function(data)
{
var html = "";
for(var i = 0; i < data.length; i++){
var uid = data[i].uid;
var firstname = data[i].firstname;
var lastname = data[i].lastname;
var email = data[i].email;
var username = data[i].username;
var password = data[i].password;
html += "<b>uid: </b>"+uid+"<b> firstname: </b>"+firstname+"<b> lastname: </b>"+lastname+"<b> email: </b>"+email+"<b> username: </b>"+username+"<b> password: </b>"+password;
}
$("#output").html( html );
}
});
});
</script>
</body>
</html>
the output is stored in var html what should I need to convert it into table format.

Just change this part of code to format table instead just bold text:
...
var html = "<table>";
html += "<thead><tr><th>UID</th><th>First Name</th><th>Last Name</th><th>Email</th><th>Username</th><th>Password</th></tr></thead>";
html += "<tbody>";
for(var i = 0; i < data.length; i++){
html += "<tr>";
var uid = data[i].uid;
var firstname = data[i].firstname;
var lastname = data[i].lastname;
var email = data[i].email;
var username = data[i].username;
var password = data[i].password;
html += "<td>"+uid+"</td><td>"+firstname+"</td><td>"+lastname+"</td><td>"+email+"</td><td>"+username+"</td><td>"+password+"</td></tr>";
}
html +="</tbody></table>";
...

I hope that's what you mean.
Try:
var html = "<table>";
html += "<thead>";
html += "<tr>";
html += "<th>Uid</th>";
html += "<th>Firstname</th>";
html += "<th>Lastname</th>";
html += "<th>Email</th>";
html += "<th>Username</th>";
html += "<th>Password</th>";
html += "<tr>";
html += "</thead>";
html += "<tbody>";
for (var i = 0; i < data.length; i++) {
var uid = data[i].uid;
var firstname = data[i].firstname;
var lastname = data[i].lastname;
var email = data[i].email;
var username = data[i].username;
var password = data[i].password;
html += "<tr>";
html += "<td>" + uid + "</td>";
html += "<td>" + firstname + "</td>";
html += "<td>" + lastname + "</td>";
html += "<td>" + email + "</td>";
html += "<td>" + username + "</td>";
html += "<td>" + password + "</td>";
html += "</tr>";
}
html += "</tbody>";
$("#output").html(html);

You can either directly create the Table within Javascript or within the PHP Script that returns the JSON Data however since you didn't show us your PHP Script, we'd go the Javascript Route like so:
<script id="source" language="javascript" type="text/javascript">
$(function () {
$.ajax({
url : 'example.php',
data : "",
dataType: 'json',
success : function(data) {
var html = "<table class='data-tbl'>";
html += "<tr class='data-head-row'>";
html += "<th class='data-head-cell'>UID</th>";
html += "<th class='data-head-cell'>First Name</th>";
html += "<th class='data-head-cell'>Last Name</th>";
html += "<th class='data-head-cell'>Email</th>";
html += "<th class='data-head-cell'>Username</th>";
html += "<th class='data-head-cell'>Password</th>";
html += "</tr>";
html += "<tbody class='data-content-body'>";
for(var i = 0; i < data.length; i++){
var uid = data[i].uid;
var firstname = data[i].firstname;
var lastname = data[i].lastname;
var email = data[i].email;
var username = data[i].username;
var password = data[i].password;
html += "<tr class='data-content-row'>";
html += "<td class='data-content-cell'>" + uid + "</td>";
html += "<td class='data-content-cell'>" + firstname + "</td>";
html += "<td class='data-content-cell'>" + lastname + "</td>";
html += "<td class='data-content-cell'>" + email + "</td>";
html += "<td class='data-content-cell'>" + username + "</td>";
html += "<td class='data-content-cell'>" + password + "</td>";
html += "</tr>";
}
html += "</tbody>";
html += "</table>";
$("#output").html( html );
}
});
});
</script>

Related

Dynamically form not submitting properly AJAX PHP

I am trying to generate dynamically form in table and submit but there is problem in my code which is difficult for me solve,
$(document).ready(function() {
$('#btnsummary').on('click', function() {
var date = $('#dddeliverydate').val();
var soid = $('#sssoid option:selected').val();
$.ajax({
url: "tblsum.php",
method: "POST",
dataType: 'JSON',
data:
"&date=" +
date +
"&soid=" +
soid,
success: function(response) {
if ( response.length == 0 ) {
alert("NO DATA FOUND!");
}
else{
$("#tblsum tbody").empty();
var len = response.length;
for(var i=0; i<len; i++){
var invoiceno = response[i].invoiceno;
var shopname = response[i].shopname;
var paymentmode = response[i].paymentmode;
var finalamount = response[i].finalamount;
if (finalamount==0){
return false
}
else if (paymentmode=="Credit"){
var tr_str = "<tr>" +
"<td align='center'>" + invoiceno + "<input type='hidden' name='invoiceno[]' value='"+invoiceno+"'></td>" +
"<td align='center'>" + shopname + "</td>" +
"<td align='center'>" + paymentmode + "</td>" +
"<td align='center'>" + finalamount + "</td>" +
"<td align='center'><input type='number' id='finalamount' name='finalamount[]' value='0'></td>" +
"</tr>";
$("#tblsum tbody").append(tr_str);
}
else{
var tr_str = "<tr>" +
"<td align='center'>" + invoiceno + "<input type='hidden' name='invoiceno[]' value='"+invoiceno+"'></td>" +
"<td align='center'>" + shopname + "</td>" +
"<td align='center'>" + paymentmode + "</td>" +
"<td align='center'>" + finalamount + "</td>" +
"<td align='center'><input type='number' id='finalamount' name='finalamount[]' value='" + finalamount + "'></td>" +
"</tr>";
$("#tblsum tbody").append(tr_str);
}
}
$("#tblsum tbody").append("<tr><td colspan='5'><button class='btn btn-success' type='button' id='btnsum'onclick='summary()'>Save</button></td></tr>");
}
}
})
});
})
There is two problem if final amount is 0 then save button did not appear, when I submit form first field which is invoiceno don't submit on next page,
below is submit function
function summary(){
$(document).ready(function(e) {
var date = $('#dddeliverydate').val();
var soid = $('#sssoid option:selected').val();
var form = $('#formsum').serialize();
$.ajax({
url: "test.php",
method: "POST",
data:
"&date=" +
date +
"&soid=" +
soid+
"&form=" +
form,
success: function(data) {
var w = window.open('about:blank', 'windowname');
w.document.write(data);
}
})
})
}
Below is my PHP code.
for($count = 0; $count<count($_POST['invoiceno']); $count++){
$data = array(
$invoiceno = $_POST['invoiceno'][$count],
$amount = $_POST['finalamount'][$count],
);
echo "Invoice NO ".$invoiceno." Amount ".$amount.'<br>';
}
sorry for bad english.
I told you before return STOPS executing a function, so all code after it is obsolete. In this case, when finalamount == 0 you stop executing the function and return to the place where it started. So the code to create the submit button never will be reached. With some proper indentation, you could see that:
$(document).ready(function() {
//<< ===== START START START of onclick function
$('#btnsummary').on('click', function() {
....
$.ajax({
url: "tblsum.php",
....
success: function(response) {
if ( response.length == 0 ) { .... }
else{
$("#tblsum tbody").empty();
....
for(var i=0; i<len; i++){
var invoiceno = response[i].invoiceno;
var finalamount = response[i].finalamount;
....
if (finalamount==0){
return false
// STOP EXECUTING THIS FUNCTION
// AND GO DIRECTLY TO END OF FUNCTION ================= >>
// code after this will NOT be executed
}
else if (paymentmode=="Credit"){....}
else{....}
}
// if finalamount == 0, this will never be executed
$("#tblsum tbody").append("<tr><td colspan='5'><button class='btn btn-success' type='button' id='btnsum'onclick='summary()'>Save</button></td></tr>");
}
}
})
});
// ===== END END END of onclick function << ===============
// continue executing script from here
})
So you could use continue instead of return to skip only one itteration in the for loop.

jQuery.Deferred exception: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefined

$.post("#", params).then(function (response) {
if (obj['error'] != 1) {
var html = '';
for (var i = 0; i < response['data'].length; i++) {
console.log('data' + i, response['data'][i]);
html += '<tr>';
html += '<td>' + response['data'][i]['wallet_type'] + '</td>';
html += '<td>' + response['data'][i]['balance'] + '</td>';
html += '<td>' + response['data'][i]['wallet_address'] + '</td>';
html += '</tr>';
}
}
});
I found
Uncaught TypeError: Cannot read property 'length' of undefined
in the console for that i cannot able to display my result.
First you need to check your response array in console something missing in your response.i think your response array does not set.
ex. console.log(response);
<script>
var response={"data":[{"id":556,"user_id":333,"email":"alokkr#dispostable.com","name":"alokkr#dispostable.com","wallet_id":"5ab7dfaa39062807cc3d0659a5ee9634","wallet_address":"QNqpGLNDhsCLWsqbz4joJHnh7QBQYhWQhz","wallet_type":"ltc","balance":0,"is_custom":false,"is_test":"0","created":"2018-03-25T17:44:50","updated":null},],"error":0,"msg":[]}
//console.log(response['data'].length);
var html='';
for (var i = 0; i < response['data'].length; i++) {
console.log('data' + i, response['data'][i]);
html += "<table border='1'>";
html += "<tr>";
html += '<td>' + response['data'][i]['wallet_type'] + '</td>';
html += '<td>' + response['data'][i]['balance'] + '</td>';
html += '<td>' + response['data'][i]['wallet_address'] + '</td>';
html += '</tr>';
html += '</table>';
}
document.write(html);
</script>

if condition php reports generation

I created a Reports module in a medication administration webapp.
A medication can be stopped, and when it happens, it's value in the database turns to 1 (1=stopped 0=active). I need the report to show "STOPED" in the "administered by" column instead of the administrator's name when a medication is stopped so here is my code, but it's not working :( It returns "STOPED" for everything. What am I doing wrong ?
Any help will be appreciated!
for (var i = 0; i < medi.length; i++) {
keys_str += "<tr>";
keys_str += "<td>" + medi[i].date + "</td>";
if (medi[i].isprn == 'y' || medi[i].isprn == "Y")
keys_str += "<td>PRN</td>";
else
keys_str += "<td>" + medi[i].time + "</td>";
keys_str += "<td>" + medi[i].medicationame + "</td>";
keys_str += "<td>" + medi[i].dosage + "</td>";
if (medi[i].is_stop !== '1' || medi[i].is_stop !== "1")
keys_str += "<td>STOPED</td>";
else
keys_str += "<td>" + medi[i].administeredby + "</td>";
keys_str += "<td>" + medi[i].witness + "</td>";
keys_str += "<td>" + medi[i].notes + "</td>";
keys_str += "<td > <img width='150px' src='" + medi[i].e_sign + "' /></td>";
keys_str += "</tr>";
}
$("#medication_hid_pdf").html();
$("#medication_hid_pdf").html(keys_str);
var date;
var time;
var medicationame;
var dosage;
var addministered;
var witness;
var str = "";
var count = 0;
for (property in medi) {
if (medi.hasOwnProperty(property)) {
str += "<tr class='gradeX'>";
date = medi[count].date;
time = medi[count].time;
medicationame = medi[count].medicationame;
dosage = medi[count].dosage;
addministered = medi[count].administeredby;
witness = medi[count].witness;
mid = medi[count].id;
str += "<td>" + date + "</td>";
if (medi[count].isprn == 'y' || medi[count].isprn == "Y")
str += "<td>PRN</td>";
else
str += "<td>" + time + "</td>";
str += "<td>" + medicationame + "</td>";
str += "<td>" + dosage + "</td>";
if (medi[count].is_stop !== '1' || medi[count].is_stop !== "1")
str += "<td>STOPED</td>";
str += "<td>" + addministered + "</td>";
str += "<td>" + witness + "</td>";
str += "<td>" + medi[count].notes + " </td>";
str += "<td ><img width='150px' src='" + medi[count].e_sign + "' /> </td>";
str += "</tr>";
count++;
}
}
$("#medicationreport_data").html(str);
}
});
I don't know exactly what your error is, but there is a lot of minor "issues" and messyness.
Now as this question is tagged PHP and you mention getting the data from the database I will assume that there is some PHP file giving this data to Javascript. How that is happening I cant tell by what is posted.
But my point is, that you should format as much of this data as you can on the PHP ( backend ) side of things. Most of this is stuff like:
....
if (medi[count].isprn == 'y' || medi[count].isprn == "Y")
str += "<td>PRN</td>";
else
str += "<td>" + time + "</td>";
....
if (medi[i].is_stop !== '1' || medi[i].is_stop !== "1")
keys_str += "<td>STOPED</td>";
else
keys_str += "<td>" + medi[i].administeredby + "</td>";
......
Basically we are just checking a value and changing it, so here PHP's loosly typed nature will help you more then JavaScripts weakly typed.
In PHP this would be something like this
$formatted = [];
foreach( $medi as $row ){
$data = []; //create a clean array if you have to
$data['isprn'] = strtolower($row['isprn']) == 'y' ? 'PRN' : $row['time'];
$data['is_stop'] = $row['is_stop'] != '1' ? 'STOPED' : '';
//include other stuff in $data you need
$formatted[] = $row;
}
Then if you get it clean enough, in Javascript you can do stuff like this
var str = '';
for (var i = 0; i < medi.length; i++) {
str += '<tr>';
str += '<td>' + medi[i].join('</td><td>') + '</td>';
str += '</tr>';
}
There are many many ways to do this, and there is a lot of "necessary" information missing for me to really be able to do much more. But I would "Strongly" suggest, normalizing all this data on the server side as best as can be done. Then on the client side you will really reduce the amount of work needed to display it to the end user.

Data tabulation table

basically I need help to display data in a table using the "td" and "tr" tags.
html += '<table class="table table-striped">';
for(var i in value){
if(!number_regex.test(i)){
html += '<tr>';
html += '<td>' + i + '</td>';
if(i == 'image_link'){
html += '<td> : ' + '<img src=' + value.image_link + ' alt>' + '</td>';
}
else{
html += '<td> : ' + value[i] + '</td>';
}
html += '</tr>';
}
}
html += '</table><br/>';
This is my current code where the value is an object. This outputs one "td" in each "tr". I'm trying to align 2 "td"s in one "tr". However, this cannot be accomplished through next(i) or (i+1) as it isn't a number.
This is what I have tried so far to no avail:
html += '<td>' + next(i) + '</td>';
if(next(i) == 'image_link'){
html += '<td> : ' + '<img src=' + value.image_link + ' alt>' + '</td>';
}
else{
html += '<td> : ' + value[next(i)] + '</td>';
}
and:
html += '<table class="table table-striped">';
html += '<tr>';
for(var i in value){
if(!number_regex.test(i)){
html += '<td>' + i + '</td>';
if(i == 'image_link'){
html += '<td> : ' + '<img src=' + value.image_link + ' alt>' + '</td>';
}
else{
html += '<td> : ' + value[i] + '</td>';
console.log(data);
}
for(var counter = 0; counter <= 8; counter++){
//8 because there are 9 fields in the query I want to display
if(counter % 2 == '0'){
html += '</tr>';
html += '<tr>';
}
}
}
Any idea guys?
These are the additional information that some of you requested:
A picture of the table I have atm:
https://www.dropbox.com/s/kmhkwturtmcxovh/lala.png
and as for the html, this is a javascript syntax, which is why I'm using html in this manner.
Take a variable and place it in the loop, which does the job of ending the rows by adding </tr>...something like :
This is what you have right now :
html += '</tr>';
amend it to something like :
$var = 0; /* initiaize it somewhere outside for(var i in value) */
if(++$var < 2)
{
/* do not echo </tr> if 2 td's haven't been added */
}
else /* 2 td's have been added, end this row */
{
$var = 0; /* reset counter*/
html += '</tr>'; /* end rows */
}

JSON output not being displayed

I have a PHP file that gives me output in JSON Format. The code is below -
<?php
include 'configure.php';
$qr = "SELECT * FROM student_details";
$res= mysql_query($qr);
$i=0;
while($row = mysql_fetch_array($res))
{
$stud_arr[$i]["full_name"] = $row["full_name"];
$stud_arr[$i]["reg_no"] = $row["regno"];
$stud_arr[$i]["address"] = $row["address"];
$stud_arr[$i]["mark1"] = $row["mark1"];
$stud_arr[$i]["mark2"]= $row["mark2"];
$stud_arr[$i]["mark3"] = $row["mark3"];
$i++;
}
header('Content-type: application/json');
echo json_encode($stud_arr);
?>
This file when ran on my server, is giving me the result perfectly, i.e. all the student details and their marks as here -
[{"full_name":"Lohith","reg_no":"100","address":"street, lane","mark1":"90","mark2":"87","mark3":"88"},{"full_name":"Ranjeet","reg_no":"101","address":"dfkljg","mark1":"56","mark2":"45","mark3":"39"},{"full_name":"karthik","reg_no":"102","address":"askjldf","mark1":"85","mark2":"90","mark3":"100"}]
Now I am trying to display this on a HTML file using -
function getAllDetails()
{
var myTable = '' ;
myTable += '<table id="myTable" cellspacing=0 cellpadding=2 border=1>' ;
myTable += "<tr><td><b>No</b></td><td><b>Full Name</b></td><td><b>Mark1</b></td><td><b>Mark2</b></td><td><b>Mark3</b></td></tr>";var url = "json-example2.php";
$.getJSON(url, function(json) { $.each(json, function(v) {
myTable += "<tr><td>"+v.reg_no+"</td><td>"+v.full_name+"</td><td>"+v.mark1+
"</td><td>"+v.mark2+
"</td><td>"+v.mark3+
"</td></tr>"; });
$("#stud_tbl").html(myTable);});};
The above code is displaying a table but says "undefined" in each data cell of the table.
No Full Name Mark1 Mark2 Mark3
undefined undefined undefined undefined undefined
undefined undefined undefined undefined undefined
undefined undefined undefined undefined undefined
Please help on how to debug this.
The first parameter to jQuery.each() is the index of the value and second one the value.
Solution change $.each(json, function(v) { to $.each(json, function(i v) {
function getAllDetails() {
var myTable = '';
myTable += '<table id="myTable" cellspacing=0 cellpadding=2 border=1>';
myTable += "<tr><td><b>No</b></td><td><b>Full Name</b></td><td><b>Mark1</b></td><td><b>Mark2</b></td><td><b>Mark3</b></td></tr>";
var url = "data.json";
$.getJSON(url, function(json) {
$.each(json, function(i, v) {
myTable += "<tr><td>" + v.reg_no + "</td><td>"
+ v.full_name + "</td><td>" + v.mark1
+ "</td><td>" + v.mark2 + "</td><td>"
+ v.mark3 + "</td></tr>";
});
$("#stud_tbl").html(myTable);
});
};
Demo: Plunker
$.each has two parameters one is index and another is value
$.each(json, function(index, value) {
myTable += "<tr><td>" + value.reg_no + "</td><td>"
+ value.full_name + "</td><td>" + value.mark1
+ "</td><td>" + value.mark2 + "</td><td>"
+ value.mark3 + "</td></tr>";
});
try the following. Here is demo at http://jsfiddle.net/H3cjC/3/
html is
<div class="tbl">
</div>
var data='[{"full_name":"Lohith","reg_no":"100","address":"street, lane","mark1":"90","mark2":"87","mark3":"88"},{"full_name":"Ranjeet","reg_no":"101","address":"dfkljg","mark1":"56","mark2":"45","mark3":"39"},{"full_name":"karthik","reg_no":"102","address":"askjldf","mark1":"85","mark2":"90","mark3":"100"}]'
data=$.parseJSON(data);
var myTable = '' ;
myTable += '<table id="myTable" cellspacing=0 cellpadding=2 border=1>' ;
myTable += "<tr><td><b>No</b></td><td><b>Full Name</b></td><td><b>Mark1</b></td><td><b>Mark2</b></td><td><b>Mark3</b></td></tr>";var url = "json-example2.php";
$.each(data, function(i,v) {
myTable += "<tr><td>"+data[i].reg_no+"</td><td>"+data[i].full_name+"</td> <td>"+v.mark1+
"</td><td>"+data[i].mark2+
"</td><td>"+data[i].mark3+
"</td></tr>";
});
$('.tbl').html(myTable);
You must use the second parameter of the each function.
function getAllDetails()
{
var myTable = '' ;
myTable += '<table id="myTable" cellspacing=0 cellpadding=2 border=1>' ;
myTable += "<tr><td><b>No</b></td><td><b>Full Name</b></td><td><b>Mark1</b></td><td><b>Mark2</b></td><td><b>Mark3</b></td></tr>";
var url = "SCRIPTNAME.php";
$.getJSON(url, function(json) { $.each(json, function(v, x) {
console.log("REG NR = "+x.reg_no);
myTable += "<tr><td>"+x.reg_no+"</td><td>"+x.full_name+"</td><td>"+x.mark1+
"</td><td>"+x.mark2+
"</td><td>"+x.mark3+
"</td></tr>"; });
$("#stud_tbl").html(myTable);
});
}

Categories