How to display a json array in html table - javascript

Hi I am new to javascript/JS or jquery . All i know is to code in php but i want to learn JS too.
My code didnt diplay the get data from json_encode to HTML TABLE.
please help me to do this. I search all way how to that. but they always use like var but when i try to do the same i didnt display anything so i start again from basics.
what i want is to display the data get from process.php json_encode into my html table TBODY part only not the whole table.
please correct me if there are something missing.(i.e jquery plugin? where to download please)
below are my code.
For Index.html
<html>
<head>
<title>LEARN AJAX</title>
<style type="text/css">
#mytable,td{
border:0px solid blue;
}
</style>
</head>
<body>
<table>
<thead>
<th>ID No.</th>
<th>Full Name</th>
<th>Address</th>
</thead>
<tbody>
<!--*/data should go Here-- >
<!--Data from process.php-->
</tbody>
</table>
</body>
</html
For Process.php
<?php
include ('connection.php');
if (mysqli_connect_errno()) {
die('Could not connect: ' . mysql_error());
}
$return_arr = array();
$sql="SELECT * FROM members";
if ($result = mysqli_query( $conn, $sql )){
while ($row = mysqli_fetch_array($result))
{
$row_array['id'] = $row['id'];
$row_array['name'] = $row['fname'];
$row_array['address'] = $row['ad'];
array_push($return_arr,$row_array);
}
}
//echo json_encode($return_arr);
$result = json_encode($return_arr);
?>
For my DB connection:
<?php
//for MySQLi OOP
$conn = new mysqli('localhost', 'root', '', 'mydatabase');
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
?>

In your tbody just loop through the result you get from php:
<tbody>
<?php
foreach ($result as $value) {
echo "<tr><td>"+$value['id']+"</td><td>"+$value['fname']+"</td><td>"+$value['ad']+"</td></tr>";
}
?>
</tbody>

Related

Changing css depending on SQL value

I'm new to both php and jquery, and i'm trying to create a webpage which shows players and it's status based on data from my Mysql server.
The base code works, although the code scraped together from multiple youtube tutorials :)
I would like to change the opacity of a player's row when it's status is, or becomes 0 (dead).
This is the code i have so far :
pagetest.php:
<!DOCTYPE html>
<html>
<head>
<title>pagetest</title>
</head>
<body>
<table id="show">
<tr>
<td>player</td>
<td>status</td>
</tr>
</table>
<script type="text/javascript" src="../jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function() {
$('#show').load('test.php')
}, 3000);
});
</script>
</body>
</html>
test.php :
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
$conn = mysqli_connect("myserver", "myuser", "mypass", "mydb");
if ($conn-> connect_error) {
die("Connection failed:". $conn->connect_error);
}
$sql = "SELECT player, status FROM mytable";
$result = $conn->query($sql);
if ($result-> num_rows > 0) {
while ($row = $result->fetch_assoc()){
echo "<tr><td>" . $row["player"] . "</td><td>" . $row["status"] . "</td></tr>";
}
echo "</table>";
}
else {
echo "No game data available";
}
?>
</body>
</html>
I'd really appreciate your help :)
Is there any reason for using jQuery with it? If no, then you can use this code:
<body>
<?php
$conn = mysqli_connect("host", "user", "password", "database");
if ($conn-> connect_error) {
die("Connection failed:". $conn->connect_error);
}
$sql = "SELECT player, status FROM mytable";
$result = $conn->query($sql);
if ($result-> num_rows > 0) {
echo '<table id="show">
<tr>
<td>player</td>
<td>status</td>
</tr>';
while ($row = $result->fetch_assoc()){
$status = $row["status"];
$player = $row["player"];
echo "<tr style='" . ($status == 0 ? 'opacity: 0;' : '') . "'><td>" . $player . "</td><td>" . $status . "</td></tr>";
}
echo '</table>';
}
else {
echo "No game data available";
}
?>
</body>
You can do something like that:
echo '<tr class="player-status-'.$row["status"].'"><td>'. $row["player"] .'</td><td>' . $row["status"] . '</td></tr>';
Add a class to your line tr based in the $row["status"] so rendered you'll have something like this: <tr class="player-status-0"><td>cristiano ronaldo</td><td>0</td></tr>
this way you can create a style to this class with css
.player-status-0 {
opacity:
}
By the way, have thought about using ajax and return a json with the data?

Load mySql data in to HTML textBox whit PHP

I have a table of thousands of lines of code in which I have to load some data coming from a database in some of the "td" of the table ...
Wandering through SO I found several examples of uploads but all of them needed a rewrite of the whole table ...
So I ask you, is there a simpler way to pass the values ​​of a database within the table?
In simple words with a SELECT I have to be able to load data inside "td" that contain textBox.
Without the need to rewrite the table (given that there are thousands of lines) ...
I am attaching the examples I found on SO:
1° : Load data from MySQL database to HTML textboxes on button click
To load data from MySQL/MariaDB database to table you can use this code:
<!DOCTYPE html>
<?php
//This is the connection
$mysqli = new mysqli('localhost', 'root', 'DatabasePassword', 'Database Name'); ?>
<html>
<head>
<title></title>
</head>
<body>
<div class="content">
<table class='table table-bordered table-striped'>
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<?php while ($row = $mysqli->fetch_array(MYSQLI_ASSOC)): ?>
<?php foreach ($row as $key => $value): ?>
<td alt="<?=$key?>"><?=$value?></td>
<?php endforeach; ?>
<?php endwhile; ?>
</tr>
</tbody>
</table>
</div>
</body>
</html>
You want to fill a <table> with database datas?
1) Build your sql query.
2) Execute and retrieve datas.
3) Inject datas into <table> using a foreach.
<?php
//Connection to db
$db = new mysqli('127.0.0.1', 'login', 'pass', 'database');
//Query
$sql = "SELECT name, surname FROM example";
//Execution + error checking
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<?php
while($row = $result->fetch_assoc()){
//Displaying results in table rows
echo "<tr>
<td>".$row["name"]."</td>
<td>".$row["surname"]."</td>
</tr>";
}
?>
</tbody>
</table>

How to edit and delete records of MySQL database without refreshing?

I am new to ajax, I am trying to view, add, edit and delete data of mysql database without refreshing the tab or in other words using ajax on this table:
I have done the view part, *edited but I can not figure out how to edit or delete *. I know it is a very long task, but I have found no solution on the internet.. Thanks in advance
HTML Code:
<html>
<head>
<title>View Data Without refresh</title>
<script language="javascript" type="text/javascript" src="script/jquery-git.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
(function() {
$.ajax({
type: "POST",
url: "display.php",
dataType: "html",
success: function(response){
$("#responsecontainer").html(response);
}
});
});
});
</script>
</head>
<body>
<fieldset><br>
<legend>Manage Student Details</legend>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Class</th>
<th>Section</th>
<th>Status</th>
</tr>
</table>
<div id="responsecontainer" align="center"></div>
</fieldset>
<input type="button" id="display" value="Add New"/>
</body>
</html>
PHP Display Code:
<?php
include("connection.php");
$sql = "select * from tbl_demo";
$result=mysqli_query($db,$sql);
echo "<table class='myTable'>";
while($data = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td width='13.5%'>$data[0]</td>";
echo "<td width='21%'>$data[1]</td>";
echo "<td width='19.5%'>$data[2]</td>";
echo "<td width='24%'>$data[3]</td>";
echo "<td><span class='edit'>Edit</span> | <span
class='delete'>Delete</span></td>";
echo "</tr>";
}
echo "</table>";
?>
If your connection, sql query and php response is ok and
I want it to be automatically done
means you want run ajax on page loading. Then, Output of php should be at last instead in each iteration.
<?php
include("connection.php");
$sql = "select * from tbl_demo";
$result=mysqli_query($db,$sql);
$output = "<table class='myTable'>";
while($data = mysqli_fetch_row($result))
{
$output .="<tr>";
$output .="<td width='13.5%'>$data[0]</td>";
$output .="<td width='21%'>$data[1]</td>";
$output .="<td width='19.5%'>$data[2]</td>";
$output .="<td width='24%'>$data[3]</td>";
$output .="<td><span class='edit'>Edit</span> | <span
class='delete'>Delete</span></td>";
$output .="</tr>";
}
$output .="</table>";
echo $output;
?>
To make edit/delete you need to pass or redirect page with action to other page named controller. After making changes again you need to redirect index/view data page or use ajax if you don't want to refresh/redirect page.

Displaying mysql database with php and Jquery Datatables?

I have been attempting to use Jquery's datatables for the first time and the tutorials available have left me rather confused. I've done the following script trying to incorporate jquery in with my php table display that I knew was working fine. I may have something fundamentally wrong here and now I'm very stuck. Would anyone be able to clear this up? (Just trying to display a basic mysql database with jquery datatables.) Thanks very much in advance.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Sid, Fname, Lname, Email, Dtype, Mac, Date FROM StudentDeviceReg";
$result = $conn->query($sql);
<script src="media/js/jquery.js" type="text/javascript"></script>
<script src="media/js/jquery.dataTables.js" type="text/javascript"></script>
<style type="text/css">
#import "media/css/demo_table.css";
</style>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#datatables').dataTable();
})
</script>
if ($result->num_rows > 0) {
echo "<table id="datatables" class="display">
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Device</th>
<th>Mac Address</th>
<th>Date</th>
</tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["Sid"]."</td>
<td>".$row["Fname"]."</td>
<td>".$row["Lname"]."</td>
<td>".$row["Email"]."</td>
<td>".$row["Dtype"]."</td>
<td>".$row["Mac"]."</td>
<td>".$row["Date"]."</td>
</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
The following section need to be either echoed or declared outside php brackets
?>
<script src="media/js/jquery.js" type="text/javascript"></script>
<script src="media/js/jquery.dataTables.js" type="text/javascript"></script>
<style type="text/css">
#import "media/css/demo_table.css";
</style>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#datatables').dataTable();
})
</script>
<?php
ALSO the section below require escape sequence or a single quote:
echo "<table id=\"datatables\" class=\"display\">
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Device</th>
<th>Mac Address</th>
<th>Date</th>
</tr>";
what do you mean error on this line?
echo "<table id="datatables" class="display">
You should note the double quotes in the attribute table, it signifies the closing echo. you can use a single quote.
echo "<table id='datatables' class='display'>
or use the backslash.
echo "<table id="\datatables\" class="\display\">

How to pass PHP value to Javascript and redirect to other page?

Why is it that I cant pass a value from my PHP code to an OnClick function on my button to my javascript function depCheck2()? I would like to redirect it to 2 different pages depending on the value it carries. Could anyone please help me?
<html>
<head>
<?php
$company_id = $_GET['cont'];
$query = "SELECT count(Department_ID) as countDep FROM department WHERE Company_ID=$company_id";
$result = mysql_query($query, $db) or die(mysql_error($db));
$row = mysql_fetch_array($result);
extract($row);
?>
<script>
function depCheck2(x){
var CountRow = '<?php echo "$countDep";?>';
if (CountRow>0){
window.location.assign("editEvent.php?id="+x"");
}
else{
window.location.assign("editEvent.php2?id="+x"");
}
}
</script>
</head>
<body>
<?php
include("config.php");
$company_id = $_GET['cont'];
$query = "select * from event_details where Company_ID=".$company_id." ORDER BY EventDetails_ID DESC";
$result=mysql_query($query, $db) or die(mysql_error($db));
echo "<table border=1 width='1000'>";
echo "<tr><th>Serial Number</th><th>Status</th><th>Event Type</th><th>Date of Event</th><th>End Date</th><th>Details</th></tr>";
while ($row = mysql_fetch_array($result))
{
extract($row);
echo "
<tr>
<td align='center'>$EventDetails_ID</td>
<td align='center'>$Status</td>
<td align='center'>$EventType</td>
<td align='center'>$StartDate</td>
<td align='center'>$EndDate</td>
<td align='center'>
<input type='button' value='Details' class='btn btn-large btn-primary' onClick='depCheck2(\''.$EventDetails_ID.'\')'>
</td>
</tr>
";
}
?>
</table>
</body>
</html>
At first: <?php echo "$countDep";?> contains $countDep which is not defined in PHP.
It is only present in the DB Query but you haven't assigned it to any variable from the $result
Then window.location.assign("editEvent.php?id="+x""); the syntax is wrong.
You have extra quotes at the end.
It should be window.location.assign("editEvent.php?id="+x);
Try this one:
window.location.href ="editEvent.php2?id="+x;

Categories