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>
I'm able to make a MySQL Database using PHP, fill it up with my data, and have it pop up on my webpage. However, I want the user to be able to click from a Options DropDown a position in Football, say QuarterBack, and then the webpage will display only the players on the team that are quarterbacks.
I'm pretty sure all I need is something to do with my line of SELECT * FROM
EDIT -- ALSO, my code on the webpage says Unidentified Index - Position, even though i define it
Relevant Code information is here:
<form action="FinalProject.php" method="get">
<select name="position" id="position" value="position">
<option value="">Select a position:</option>
<option value="1">Quarterback</option>
<option value="2">Wide Receiver</option>
<option value="3">Linebacker</option>
<option value="4">Tight End</option>
</select>
</form>
<?php
// --- CREATE THE DATABASE
$db_conn = mysqli_connect("localhost", "root", "");
if (!$db_conn)
die("Unable to connect: " . mysqli_connect_error());
mysqli_query($db_conn, "CREATE DATABASE IF NOT EXISTS sportDatabase;");
// --- CREATE THE TABLE
mysqli_select_db($db_conn, "sportDatabase");
$cmd = "CREATE TABLE bearsRoster (
number int(2) NOT NULL PRIMARY KEY,
playerName varchar(20),
position char(2),
height varchar(5),
weight int(3),
age int(2),
experience int(2),
collegeName varchar(50)
);";
mysqli_query($db_conn, $cmd);
$cmd = "LOAD DATA LOCAL INFILE 'bearsRoster.csv' INTO TABLE bearsRoster FIELDS TERMINATED BY ',';";
mysqli_query($db_conn, $cmd);
$selectedOption = $_GET["position"];
$cmd = "SELECT * FROM bearsRoster ";
// ORDER BY position WHERE".$selectedOption.";";
$records = mysqli_query($db_conn, $cmd);
echo("<table border = 'black' align:'center'>
<tr>
<th>Number</th>
<th>Player Name</th>
<th>Position</th>
<th>Height</th>
<th>Weight</th>
<th>Age</th>
<th>Experience</th>
<th>College Name</th>
</tr>" . PHP_EOL);
while ($row = mysqli_fetch_array($records)) {
echo("<tr>
<td id = 'yellow'>" . $row['number'] . "</td>
<td id = 'red'>" . $row['playerName'] . "</td>
<td id = 'red'>" . $row['position'] . "</td>
<td id = 'blue'>" . $row['height'] . "</td>
<td id = 'blue'>" . $row['weight'] . "</td>
<td id = 'pink'>" . $row['age'] . "</td>
<td id = 'pink'>" . $row['experience'] . "</td>
<td id = 'pink'>" . $row['collegeName'] . "</td>
</tr>" . PHP_EOL);
}
echo("</table>");
mysqli_close($db_conn);
?>
I edited your code a bit and I this should work.
<form action="FinalProject.php" method="POST">
<select name="position" id="position" value="position">
<option value="">Select a position:</option>
<option value="QB">Quarterback</option>
<option value="WR">Wide Receiver</option>
<option value="LB">Linebacker</option>
<option value="TE">Tight End</option>
</select>
<input type="submit" name="submit" value="Click me!" />
</form>
<?php
$db_conn = mysqli_connect("localhost", "root", "");
if (!$db_conn)
die("Unable to connect: " . mysqli_connect_error());
mysqli_query($db_conn, "CREATE DATABASE IF NOT EXISTS sportDatabase;");
mysqli_select_db($db_conn, "sportDatabase");
$cmd = "CREATE TABLE bearsRoster (number int(2) NOT NULL PRIMARY KEY, playerName varchar(20), position char(2), height varchar(5), weight int(3), age int(2), experience int(2), collegeName varchar(50));";
mysqli_query($db_conn, $cmd);
$cmd = "LOAD DATA LOCAL INFILE 'bearsRoster.csv' INTO TABLE bearsRoster FIELDS TERMINATED BY ',';";
mysqli_query($db_conn, $cmd);
$cmd = "SELECT * FROM bearsRoster";
if(isset($_POST['submit'])) {
if($_POST['position'] == 'QB' || $_POST['position'] == 'WR' || $_POST['position'] == 'LB' || $_POST['position'] == 'TE')
$selectedOption = $_POST['position'];
else
$selectedOption = null;
if($selectedOption !== null)
$cmd = "SELECT * FROM bearsRoster WHERE position = ".$selectedOption.";";
}
$records = mysqli_query($db_conn, $cmd);
echo("<table border = 'black' align:'center'><tr><th>Number</th><th>Player Name</th><th>Position</th><th>Height</th><th>Weight</th><th>Age</th><th>Experience</th><th>College Name</th></tr>" . PHP_EOL);
while($row = mysqli_fetch_array($records)){
echo("<tr><td id = 'yellow'>" . $row['number'] . "</td><td id = 'red'>" . $row['playerName'] . "</td><td id = 'red'>" . $row['position'] . "</td><td id = 'blue'>" . $row['height'] . "</td><td id = 'blue'>". $row['weight'] . "</td><td id = 'pink'>". $row['age'] . "</td><td id = 'pink'>". $row['experience'] . "</td><td id = 'pink'>". $row['collegeName'] . "</td></tr>". PHP_EOL);
}
echo("</table>");
mysqli_close($db_conn);
Use IF NOT EXISTS in your table creation as this will delete and create your table each time you run the script. You can use AJAX to fetch data from the server without reloading the page or redirecting.
AJAX is a developer's dream, because you can:
Update a web page without reloading the page
Request data from a server - after the page has loaded
Receive data from a server - after the page has loaded
Send data to a server - in the background
In your select add onchange attribute that will call a Javascript function which will fetch the data from the database and display it on the page without reloading.
HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select name="position" id="position" onchange="getPosition(this)" value="position">
<option value="">Select a position:</option>
<option value="QB">Quarterback</option>
<option value="WR">Wide Receiver</option>
<option value="LB">Linebacker</option>
<option value="TE">Tight End</option>
</select>
<div id="results"></div>
<script>
function getPosition(position) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("results").innerHTML = this.responseText;
}
};
xhttp.open("POST", "FinalProject.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('position=' + position.value);
}
</script>
</body>
</html>
FinalProject.php
<?php
// --- CREATE THE DATABASE
$db_conn = mysqli_connect("localhost", "root", "");
if (!$db_conn)
die("Unable to connect: " . mysqli_connect_error());
mysqli_query($db_conn, "CREATE DATABASE IF NOT EXISTS sportDatabase;");
// --- CREATE THE TABLE
mysqli_select_db($db_conn, "sportDatabase");
$cmd = "CREATE TABLE IF NOT EXISTS bearsRoster (
number int(2) NOT NULL PRIMARY KEY,
playerName varchar(20),
position char(2),
height varchar(5),
weight int(3),
age int(2),
experience int(2),
collegeName varchar(50)
);";
mysqli_query($db_conn, $cmd);
$cmd = "LOAD DATA LOCAL INFILE 'bearsRoster.csv' INTO TABLE bearsRoster FIELDS TERMINATED BY ',';";
mysqli_query($db_conn, $cmd);
$selectedOption = $_POST["position"];
$cmd = "SELECT * FROM `bearsRoster` WHERE position = '$selectedOption' ORDER BY position";
$records = mysqli_query($db_conn, $cmd);
if ($records && mysqli_num_rows($records)) : ?>
<table border='black' align="center">
<tr>
<th>Number</th>
<th>Player Name</th>
<th>Position</th>
<th>Height</th>
<th>Weight</th>
<th>Age</th>
<th>Experience</th>
<th>College Name</th>
</tr>
<?php while ($row = mysqli_fetch_array($records)) : ?>
<tr>
<td id='yellow'><?php echo $row['number']; ?></td>
<td id='red'><?php echo $row['playerName']; ?></td>
<td id='red'><?php echo $row['position']; ?></td>
<td id='blue'><?php echo $row['height']; ?></td>
<td id='blue'><?php echo $row['weight']; ?></td>
<td id='pink'><?php echo $row['age']; ?></td>
<td id='pink'><?php echo $row['experience']; ?></td>
<td id='pink'><?php echo $row['collegeName']; ?></td>
</tr>
<?php endwhile; ?>
</table>
<?php else: ?>
<h1>No Data found</h1>
<?php endif;
mysqli_close($db_conn);
?>
in the code i used csv file in which i want to edit the rows of 3rd coulmn as want to make them a http link by using tag but i cant do that. right now the code chowing only the link but i want to make them hyperlink
<html>
<head>
</head><body>
<table width="10%" cellpadding="1" cellspacing="0" border="1" ;">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<?php
$f = fopen("http://localhost/csv/cr.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
$data = count($line);
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
?>
</tr>
</thead>
</table>
</body>
</head>
try:
<?php
$f = fopen("http://localhost/csv/cr.csv", "r");
while (($line = fgetcsv($f)) !== false) {
if (!isset($line[2])) {
continue;
}
echo "<tr><td><a href='url'>" . htmlspecialchars($line[2]) . "</a></td></tr>";
}
fclose($f);
?>
I'm writing 2 queries and the first query is working fine but the 2nd query is not working. Please, Guide me.Thanks.
<table class="table table-bordered table-hover">
<form role="form" method="post" action="">
<div class="tablenav top">
<div class="alignleft actions bulkactions">
<label for="bulk-action-selector-top" class="screen-reader-text">Comment Action</label><select name="comment_status" id="bulk-action-selector-top">
<option value="" name="">Select Option</option>
<option value="Approve" name="Approve">Approve</option>
<option value="unapprove" name="unapprove" class="hide-if-no-js">Unapprove</option>
</select>
<input type="submit" name="submit" id="doaction" class="button action" value="Apply">
</div>
<br class="clear">
</div>
<thead>
<tr>
<th></th>
<th>Id</th>
<th>Author</th>
<th>Comments</th>
<th>Email</th>
<th>Author Url</th>
<th>Status</th>
<th>Date</th>
<th>Post Name</th>
<th>Edit</th>
<th>Delete</th>
<th>Reply</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM comments";
global $connection;
$select_comments = mysqli_query($connection, $query) or die('Could not look up user information; ' . mysqli_error($connection));
while ($row = mysqli_fetch_array($select_comments)) {
$comment_id = $row['comment_id'];
$comment_post_id = $row['comment_post_id'];
$comment_author = $row['comment_author'];
$comment_date = $row['comment_date'];
$comment_email = $row['comment_email'];
$comment_author_url = $row['comment_author_url'];
$comment_content = $row['comment_content'];
$comment_status = $row['comment_status'];
echo "<tr>
<td><input type='checkbox' name='check_list[]' value='$comment_id'></td>
<td>$comment_id</td>
<td>$comment_author</td>
<td>$comment_content</td>
<td>$comment_email</td>
<td>$comment_author_url</td>
<td>$comment_status</td>
<td>$comment_date</td>
</tr>";
}
if (isset($_POST['submit'])) {
global $connection;
global $errors;
$comment_status = $_POST['comment_status'];
$check_box = isset($_POST['check_list']) ? $_POST['check_list'] : '';
// error messages
$missingcheckbox = "<p><stong>Recored box not checked.Please check the checkbox.</strong></p>";
// for name feild
if (!$check_box) {
$errors .= $missingcheckbox;
}
if ($errors) {
$resultMessage = '<div class="alert alert-danger">' . $errors . '</div>';
echo $resultMessage;
} else {
for ($i = 0; $i < count($_POST['check_list']); $i++) {
$id = $_POST['check_list'][$i];
if ($comment_status == 'Approve') {
$query = "UPDATE comments SET comment_status = 'approved' WHERE comment_id = $id";
} elseif ($comment_status == 'Unapprove') {
$query = "UPDATE comments SET comment_status = 'unapproved' WHERE comment_id = $id";
}
if ($approve_comments = mysqli_multi_query($connection, $query)) {
// header ("location: comments.php");
// exit;
$resultMessage = '<div class="alert alert-success">Data has been successfully Updated.<img src="../../assets/img/refresh.png" alt="Edit Client" title="Refresh" style="width:30px; height:30px; border:0;"></div>';
echo $resultMessage;
} else {
$resultMessage = '<div class="alert alert-warning">ERROR: Unable to excecute:' . $query . ' . ' . mysqli_error($connection) . '</div>';
echo $resultMessage;
}
}
}
}
?>
</tbody>
</table>
The first query is working fine but 2nd query is not working.I have problem in this code below:-
if($comment_status =='Approve'){
$query = "UPDATE comments SET comment_status = 'approved' WHERE comment_id = $id";
}elseif($comment_status =='Unapprove'){
$query = "UPDATE comments SET comment_status = 'unapproved' WHERE comment_id = $id";
}
Case matters when comparing two strings to be the same
<option value="unapprove"
^^^
and
elseif($comment_status =='Unapprove'){
^^^
$id its a variable and you are putting there as string. Example:
<?php
$a = "Hello ";
$b = $a . "World!"; // "Hello World!"
$a = "Hello ";
$a .= "World!"; // "Hello World!"
?>
You must do the same.
Currently I'm learning Server Sent Events. Everything is fine if I make a simple HTML application. But when I turn into AngularJS, the problem appears. Server Sent Events is not continually called in Firefox. It works only once. This problem doesn't happen in Chrome and Opera.
Is this some issues regarding AngularJS performance in Firefox? Or is there anything wrong with my code? Any answer would be very appreciated! Thanks.. :)
Index.php
<body ng-app='' ng-controller="myCtrl">
<table class="table table-bordered table-hover table-responsive table-striped">
<thead>
<tr>
<th>No.</th>
<th>Id</th>
<th>Name</th>
<th>Level</th>
<th>Hapus</th>
</tr>
</thead>
<tr ng-repeat="x in admin">
<td>
{{$index + 1}}.
</td>
<td>
<input type="text" value="{{x.Id}}" class="init" readonly>
</td>
<td>
<textarea ng-keyup="myFunc($event, x.Id, 'Name')" class="init" ng-focus="edit($event)" ng-blur="noedit($event, x.Id, 'Name')">{{x.Name}}</textarea>
</td>
<td>
<textarea ng-keyup="myFunc($event, x.Id, 'Level')" class="init" ng-focus="edit($event)" ng-blur="noedit($event, x.Id, 'Level')">{{x.Level}}</textarea>
</td>
<td>
<button ng-click="sendDelete(x.Id)" class="btn btn-warning">Hapus</button>
</td>
</tr>
</table>
<div id="result"></div>
<script src="js/jquery-1.9.1.js" type="text/javascript"></script>
<script src="js/angular-1.2.25.min.js" type="text/javascript"></script>
<script type="text/javascript">
function myCtrl($scope, $http, $window) {
if (typeof (EventSource) !== "undefined") {
// Yes! Server-sent events support!
var source = new EventSource("sse.php");
source.onmessage = function(event) {
msg = JSON.parse(event.data);
$scope.admin = msg;
$scope.$apply();
document.getElementById("result").innerHTML += msg.Id + ". " + msg.Name + ". " + msg.Level + "<br>";
console.log($scope.admin);
};
} else {
// Sorry! No server-sent events support..
alert('SSE not supported by browser.');
}
};
</script>
</body>
sse.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
require_once 'koneksi.php';
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = "SELECT * FROM `admin` WHERE id='" . $id . "'";
} else {
$query = "SELECT * FROM `admin`";
}
$stmnt = $dbh->prepare($query);
$stmnt->execute();
$output = "[";
while ($row = $stmnt->fetch()) {
if ($output != "[") {
$output .= ",";
}
$output .= '{"Id":"' . $row["id"] . '",';
$output .= '"Name":"' . $row["name"] . '",';
$output .= '"Level":"' . $row["level"] . '"}';
}
$output .= "]";
echo 'data: ' . ($output) . "\n\n";
ob_flush();
flush();
sleep(1);
?>