Bootstrap Data Tables with MySQL content - php

I have a form in which a user select a reference of a candelabra.
When the choice done, a list of incidents relative to the candelabra appears in a bootstrap table.
The table is completed with items from a Mysql database.
All is ok. Now I'd like to add a button in another column called "test". But I have no buttons.. I put a screenshot of what I see..
My code is this one :
FORM FILE
<?php
require_once 'login.php';
$sql= "SELECT ptlum FROM ptlum where ptlum LIKE '%AZ%'";
$result = mysql_query($sql) or die("Requete pas comprise");
//while($data = mysql_fetch_array($result))
// {
//echo "<option>".$data[ptlum]."</option>";
// }
?>
<html>
<head>
<meta charset="utf-8">
<link href="examples.css" rel="stylesheet">
<link href="http://minikomi.github.io/Bootstrap-Form-Builder/assets/css/lib/bootstrap.min.css" rel="stylesheet">
<link href="http://minikomi.github.io/Bootstrap-Form-Builder/assets/css/lib/bootstrap-responsive.min.css" rel="stylesheet">
<link href="http://minikomi.github.io/Bootstrap-Form-Builder/assets/css/custom.css" rel="stylesheet">
<link href="bootstrap.table.css" rel="stylesheet">
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form class="form-horizontal" >
<legend>Rechercher une panne en cours ou archivée</legend>
<div class="control-group">
<label class="control-label" for="selectbasic-0">Sélectionner un point lumineux</label>
<div class="controls">
<select name="users" onchange="showUser(this.value)">
<?php
while ($row = mysql_fetch_array($result))
{
echo "<option>".$row[ptlum]."</option>";
}
?>
</select>
</div>
</div>
</form>
<script src= "jquery.js"></script>
<script src= "bootstrap.min.js"></script>
<script src= "bootstrap.table.js"></script>
<br>
<div id="txtHint"><b></b></div>
</body>
</html>
PHP FILE WITH CALLING THE DATABASE
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet">
</head>
<body>
<script src= "jquery.js"></script>
<script src= "https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<script src= "https://cdn.datatables.net/1.10.9/js/dataTables.bootstrap.min.js"></script>
<?php
$q = $_GET['q'];
//echo $q;
$con = mysqli_connect('localhost','root','root','sdeer');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM depannages WHERE ptlum = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table id=\"example\" class=\"table table-striped table-bordered\" cellspacing=\"0\" width=\"100%\">
<tr>
<th>Pt Lum</th>
<th>Matériel</th>
<th>Prestation</th>
<th>Date</th>
<th>Nature</th>
<th>Test</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tbody>";
echo "<tr>";
echo "<td>" . $row['ptlum'] . "</td>";
echo "<td>" . $row['materiel'] . "</td>";
echo "<td>" . $row['presta'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['nature'] . "</td>";
echo "</tr>";
echo "</tbody>";
}
echo "</table>";
mysqli_close($con);
?>
<script>
$(document).ready(function() {
var table = $('#example').DataTable( {
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
</script>
</body>
</html>
How to make it if I want to have a button ? When the user will click on the button, a new window will appear.
Thanks !

You can make a anchor tag look like as button. Just you need to add role="button".
New Window Button
Edited Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="stylesheet">
<script src= "jquery.js"></script>
<script src= "https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<script src= "https://cdn.datatables.net/1.10.9/js/dataTables.bootstrap.min.js"></script>
</head>
<body>
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','root','sdeer');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM depannages WHERE ptlum = '$q'";
$result = mysqli_query($con,$sql);
?>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Pt Lum</th>
<th>Matériel</th>
<th>Prestation</th>
<th>Date</th>
<th>Nature</th>
<th>Test</th>
</tr>
</thead>
<tbody>
<?
while($row = mysqli_fetch_array($result))
{?>
<tr>
<td><?echo $row['ptlum'];?></td>
<td><?echo $row['materiel'];?></td>
<td><?echo $row['presta'];?></td>
<td><?echo row['date'];?></td>
<td><?echo $row['nature'];?></td>
<td>
New Window Button
</td>
</tr>
<?}?>
<tbody>
</table>
<?mysqli_close($con);?>
<script>
$(document).ready(function() {
var table = $('#example').DataTable( {
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
</script>
</body>
</html>

Related

Query String PHP

I'm trying to get the Owner's details by clicking on their name from the table at the bottom.
<html>
<head>
<title>Home</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('co'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
<?php
require 'Navbar.php';
?>
<h1>Welcome to Poppleton Dog Show! This year 50 owners entered 300 dogs in 10 events!</h1>
<?php
include './connection.php';
$sql = "SELECT owners.id AS id, owners.name AS Owner, owners.email AS Email, dogs.name AS Name, ROUND(avg(score), 1) AS avg_score, breeds.name AS breed_name, COUNT(entries.id) AS entries_count\n"
. "FROM entries\n"
. "JOIN dogs ON dogs.id = entries.dog_id\n"
. "JOIN breeds ON dogs.breed_id = breeds.id\n"
. "JOIN owners ON owners.id = dogs.owner_id\n"
. "GROUP BY dogs.id\n"
. "HAVING entries_count > 1\n"
. "ORDER BY `avg_score` DESC\n"
. "LIMIT 10";
$result = $conn->query($sql);
echo "<table '<td align='center'>
<tr>
<th>Owner</th>
<th>Email</th>
<th>Dog</th>
<th>Breed</th>
<th>Average Score</th>
</tr>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>". "" ."". $row['Owner']. "</td>";
echo "<td>". "" ."<a href= mailto:$row[Email]>$row[Email]</a></td>";
echo "<td>". "" . $row["Name"] . "</td>";
echo "<td>". "" . $row["breed_name"] . "</td>";
echo "<td>". "" . $row["avg_score"] . "</td>";
echo "</tr>";
}
echo "</table>";
$conn->close();
?>
<!-- connection message will fade away-->
<script>
$( document ).ready( readyFn );
$(function() {
$('#echo').fadeOut(1000);
});
</script>
</body>
</html>
my $_GET method on the other page is now taking the number but it's still not displaying the owner's details and no errors or anything. I don't know what's wrong with the code. A would appreciate any advice regarding code, formatting, etc.
<html>
<head>
<title>OwnerDetail</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('co'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
<?php
require 'Navbar.php';
?>
<?php
include './connection.php';
?>
<?php
$id = $_GET['id']; // Collecting data from query string
if (!is_numeric($id)) { // Checking data it is a number or not
echo "Data Error";
exit;
}
$count=$dbo->prepare("SELECT * FROM owners WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
if($count->execute()){
echo " Success ";
$row = $count->fetch(PDO::FETCH_OBJ);
echo "<table>";
}
echo "
<tr bgcolor='#f1f1f1'><td><b>Name</b></td><td>$row->name</td></tr>
<tr><td><b>Class</b></td><td>$row->class</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Mark</b></td><td>$row->mark</td></tr>
<tr><td><b>Address</b></td><td>$row->address</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Image</b></td><td>$row->img</td></tr>
";
echo "</table>";
?>
<script>
$( document ).ready( readyFn );
$(function() {
$('#echo').fadeOut(1000);
});
</script>
</body>
</html>
You really should consider doing this:
Replace the ancient jQuery
Simplify the PHP which is already producing invalid HTML
Ajax the data only
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
$("#ownerTable a.owner").on("click", function(e) {
e.preventDefault(); // stop link
const ownerDetails = $.get(this.href, function(data) {
$("#output").html(data)
});
});
});
<script>
and have
<table>
<thead>
<tr>
<th>Owner</th>
<th>Email</th>
<th>Dog</th>
<th>Breed</th>
<th>Average Score</th>
</tr>
</thead>
<tbody id="ownerTable">
<? while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td>
<a class="owner" href="OwnerDetails.php?id=<?= $row['id'] ?>"><?= $row['Owner'] ?></a>
</td>
<td>
<?= $row[Email] ?>
</td>
<td>
<?= $row["Name"] ?>
</td>
<td>
<?= $row["breed_name"] ?>
</td>
<td>
<?= $row["avg_score"] ?>
</td>
</tr>
<? } ?>
</tbody>
<tbody id="output"></tbody>
</table>
where Ownerdetails.php now looks like
<?php
$id = $_GET['id']; // Collecting data from query string
if (!is_numeric($id)) { // Checking data it is a number or not
echo "<tr><td>Data Error</td></tr>";
exit;
}
$count=$dbo->prepare("SELECT * FROM owners WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
if($count->execute()){
$row = $count->fetch(PDO::FETCH_OBJ);
echo "
<tr bgcolor='#f1f1f1'><td><b>Name</b></td><td>$row->name</td></tr>
<tr><td><b>Class</b></td><td>$row->class</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Mark</b></td><td>$row->mark</td></tr>
<tr><td><b>Address</b></td><td>$row->address</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Image</b></td><td>$row->img</td></tr>";
}
?>

how to add ajax to a php file

how could i add ajax to my php file ,that when i delete an item of the list the data should automatically reload and my list should be updated to the new list?
I made list of all my data with a button of delete
here is my code for php
<?php
function tableV1 ($row) {
echo '<tr>';
echo '<td>' .$row['id']. '</td>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
}
$dbPassword = "micr2001";
$dbUserName = "PHPFundamentals";
$dbServer = "localhost";
$dbName = "PHPfundamentals";
// Create connection
$conn = mysqli_connect($dbServer , $dbUserName , $dbPassword,$dbName) or die("unable to connect to host");
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<style type="text/css">
table {font-size: 27px; }
tbody {}
td {border-bottom: 1px solid bisque;padding:15px;}
th {border-bottom: 1px solid bisque;padding:15px;}
thead {}
tr {}
</style>
</head>
<body>
<center>
<table>
<thead>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Action</th>
<th> </th>
</thead>
<?php
// Takes all the results from the table with genre 5.
$sql = "SELECT id,firstname, lastname FROM persons";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
tableV1($row);
$rowId = $row['id'];
$first_name = $row['firstname'];
$last_name = $row['lastname'];
echo '<td>'
. ' <a class="edit_btn btn" href=edit.php?id='.$rowId.'&lname='.$last_name.'&fname='.$first_name. '>Edit</a>'
. ' </td>';
echo '<td><a class="del_btn btn" href=delete.php?id='.$rowId.'>Delete</a></td>';
echo' </tr>';
}
} else {
echo '<tr><td colspan="3">0 results</td></tr>';
}
?>
</table>
</center>
</body>
</html>
<?php
$conn->close();
?>
here is the code for delete.php
<?php
require 'connection.php';
$id = $_GET['id'];
$sql = "DELETE FROM persons WHERE id = ".$id ;
if(mysqli_query($conn, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
mysqli_close($conn);
?>
i want the item that i delete should get off my list
Why do you even need AJAX? As user clicks Delete, she / he is redirected to the delete.php script. In that script after sucessful deletion you should just redirect the user back to the listing. This can be achieved by HTTP redirect (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection). Keep it simple!

multiple values not getting stored in array in php ,help me with the code below

My PHP code:
<?php
include 'function.php';
$db = mysqli_connect("localhost","root","","messmanagementsys");
session_start();
if(mysqli_connect_error())
{
echo "ERROR CONNECTING TO THE DATABASE";
}
else{
$vali=$_POST['noie'];
echo $vali;
for($i=1;$i<=$vali;$i++)
{
$iname=$_POST['ingname'.$i];
$icode=$_POST['ingcode'.$i];
$icur=$_POST['ingcur'.$i];
$ireq=$_POST['ingreq'.$i];
$icost=$_POST['ingcost'.$i];
$idate=$_POST['ingdate'.$i];
$check="SELECT `ingcode` FROM `ing` WHERE ingcode='$icode'";
$s=mysqli_query($db,$check);
$coderepeat=mysqli_fetch_array($s);
$e=mysqli_num_rows($s);
echo $e;
if($e>0)
{
echo "<script>$(function(){
$('#my-dialog-id').dialog();
});
</script>";
if(isset($_POST['ingyes']))
{
$update="UPDATE `ing` SET `ingname`='$iname',`ingcode`='$icode',`current`='$icur',`required`='$ireq',`ingcost`='$icost',`date`='$idate' WHERE 1";
}
if(isset($_POST['ingno'])){
header("Refresh:0:url=ingredient.php");
}
}
else{
$query="INSERT INTO `ing`(`ingname`, `ingcode`, `current`, `required`, `ingcost`, `date`) VALUES ('$iname','$icode','$icur','$ireq','$icost','$idate')";
$res=mysqli_query($db,$query);
if($res)
header("Refresh:0;url=ingredient.php");
else
echo "SOMETHING WENT WRONG";
}
}
}
?>
<!DOCTYPE html>
<head></head>
<body>
<form action="ingupdate.php" method="POST">
<div id='my-dialog-id' title='my dialog title'>
<p>The item <?php $string=implode(",",$coderepeat);echo $string;?> already exists do u wish to update??</p>
<button name="ingyes" >YES</button>
<button name="ingno">NO</button>
</div>
</form>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</body>
I need to print the code which is being repeated.
I have put the entries in an array in php but if i have 2 codes which are repetitive then the array has he same value stored twice.
I'm getting the values of the variable from a html page and the user selects the no of entries he wants to make.
I'm creating the input field dynamically and setting names dynamically so I'm retrieving them in PHP by concatenating ingname with $i which is a variable which is set to the no of input fields user has requested.
I'm using loops and retrieving the values of those input fields.
What can i do to enter into array the 2 values?
Here is my html code:
<!DOCTYPE html>
`<html>
<head>
<link rel="stylesheet" href="main.css">
<link href='https://fonts.googleapis.com/css?family=Bungee Shade' rel='stylesheet'>
<link href='https://fonts.googleapis.com/css?family=Eater' rel='stylesheet'>
<title>Ingredients Details</title>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<center> <h1 id="labelb">Ingredients Details</h1></center>
<form action="ingupdate.php" method="POST" >
<input type="text" name="noie" placeholder="Enter the no of ingredients to add" style="width:200px;" id="noie">
<button id="noieb">Enter</button>
<table id="ingredients">
<thead><tr>
<th>Ingredient name:</th>
<th>Ingredient code:</th>
<th>Current<sub>(in stock in kgs)</sub></th>
<th>Required<sub>(excluding stocks in kgs)</sub></th>
<th>Cost<sub>(in Rupees including transportation)</sub></th>
<th>Date:</th>
</tr>
</thead>
<tbody id="ing">
<?php
$db = mysqli_connect("localhost","root","","messmanagementsys");
session_start();
if(mysqli_connect_error())
{
echo "ERROR CONNECTING TO THE DATABASE";
}
else{
//$query1="SELECT * FROM login ";
$usr=$_SESSION['adminuser'];
$query1="SELECT * FROM `ing` WHERE 1";
$result1=mysqli_query($db,$query1);
while($row = mysqli_fetch_array($result1))
{
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>" . $row[3] . "</td>";
echo "<td>" . $row[4] . "</td>";
echo "<td>" . $row[5] . "</td>";
echo "</tr>";
}
}
//echo "<td><form action='fineedit.php' method='POST'><select name='sfstat'><option value='paid' >Paid</option><option value='unpaid' selected>No</option></select><button type='submit' name='submit'>submit</button></form></td>";
?>
</tbody>
</table>
<button type="submit" name="submit" >SUBMIT</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
document.getElementById("noieb").onclick=function()
{
var i=document.getElementById("noie").value;
for(var j=1;j<=i;j++)
{
var table = document.getElementById("ing");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
var name='ingname'+j;
var code='ingcode'+j;
var cur='ingcur'+j;
var req='ingreq'+j;
var cost='ingcost'+j;
var date='ingdate'+j;
var iname = document.createElement('input');
iname.setAttribute("type", "text");
iname.name = "ingname" + j;
iname.setAttribute("required", "true");
cell1.appendChild(iname);
var icode = document.createElement('input');
icode.setAttribute("type", "text");
icode.name = "ingcode" + j;
icode.setAttribute("required", "true");
cell2.appendChild(icode);
var icur = document.createElement('input');
icur.setAttribute("type", "number");
icur.name = "ingcur" + j;
icur.setAttribute("required", "true");
cell3.appendChild(icur);
var ireq = document.createElement('input');
ireq.setAttribute("type", "number");
ireq.name = "ingreq" + j;
ireq.setAttribute("required", "true");
cell4.appendChild(ireq);
var icost = document.createElement('input');
icost.setAttribute("type", "number");
icost.name = "ingcost" + j;
icost.setAttribute("required", "true");
cell5.appendChild(icost);
var idate = document.createElement('input');
idate.setAttribute("type", "date");
idate.name = "ingdate" + j;
idate.setAttribute("required", "true");
cell6.appendChild(idate);
}
}
function delrow(){
var table = document.getElementById("ing");
table.deleteRow(-1);
}
$(document).ready(function(){
$("input[name=edit]").on("click",function(){
$(".en").css("display","block");
})
$("input[name=save]").on("click",function(){
$(".en").css("display","none");
})
})
</script>
</body>\
Second html file
</html>
<!DOCTYPE html>
<head></head>
<body>
<form action="ingupdate.php" method="POST" >
<input type="text" name="noie" placeholder="Enter the no of ingredients to add" style="width:200px;" id="noie">
<button id="noieb">Enter</button>`
<div id='my-dialog-id' title='my dialog title'>
<p>The item <?php print_r($coderepeat);?> already exists do u wish to update??</p>
<button name="ingyes" >YES</button>
<button name="ingno">NO</button>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</body>

Table row populated by drop down selection

i have a drop down list populated from a database(it is the first cell in a table row) then based on that selection i want it to populate the rest of the row from the same database, each cell is a different table in the database, so far i only have it populating the first cell (calories), i can't figure out how to get it to populate the rest of the cells, thanks
<?php
$link=mysqli_connect("localhost", "root", "");
mysqli_select_db($link,"meal_planner");
?>
<!DOCTYPE html>
<html>
<head>
<title>Meal Planner</title>
<link href="main2.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
// Hide all panels to start
var panels = $('.accordion > dd').hide();
// Show first panel on load (optional). Remove if you want
panels.first().show();
// On click of panel title
$('.accordion > dt > a').click(function() {
var $this = $(this);
// Slide up all other panels
panels.slideUp();
//Slide down target panel
$this.parent().next().slideDown();
return false;
});
});
</script>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<dl class="accordion">
<dt>Monday</dt>
<dd>
<table>
<tr>
<th>Breakfast</th>
<th>Calories</th>
<th>Protein</th>
<th>Carbs</th>
<th>Fat</th>
<th>Serving Sizing</th>
</tr>
<tr>
<td>
<select name="breakfa"s onchange="showUser(this.value)">
<option value="">Select a Protein:</option>
<?php
$res=mysqli_query($link,"select name, protein_id from protein");
while($row=mysqli_fetch_array($res))
{
?>
<option value="<?php echo $row["protein_id"]; ?>"><?php echo $row["name"]; ?></option>
<?php
}
?>
</select>
</td>
<td><div id="txtHint"><b>0</b></div></td>
<td>50</td>
<td>50</td>
<td>50</td>
<td><input type="" name=""></td>
</tr>
</table>
</dd>
<dt>Tuesday</dt>
<dd>TEST</dd>
<dt>Wednesday</dt>
<dd>TEST.</dd>
</dl>
</body>
</html>
php
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','meal_planner');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM protein WHERE protein_id = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['calories'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>

jquery tablesorter problem

hello
i get some help here yesterday for a problem i was having tablesorter. if i run the backend query on its own it displays the results ok. but i call it from another page from dropdown it displays all records and no errors are being seen in firebug. where am i going wrong? thanks
this code works on its own.
getuserlog.php
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sample", $con);
$sql="SELECT * FROM logger_log WHERE idusr_log = '".$q."' order by datein_log desc";
$result = mysql_query($sql);
echo "<table id=\"userlog\" class=\"tablesorter\" cellspacing=\"1\">
<thead>
<tr>
<th align=\"left\">Ip Address</th>
<th align=\"left\">Date In</th>
<th align=\"left\">Date Out</th>
</tr>
</thead>";
echo "<tbody>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ip_log'] . "</td>";
echo "<td>" . date('d/m/Y H:i:s',strtotime($row['datein_log'])) . "</td>";
echo "<td>" . date('d/m/Y H:i:s',strtotime($row['dateout_log'])) . "</td>";
echo "</tr>";
}
echo"</tbody>";
echo "</table>";
mysql_close($con);
?>
<div id="pager" class="pager">
<form>
<img src="css/blue/first.png" class="first"/>
<img src="css/blue/prev.png" class="prev"/>
<input type="text" class="pagedisplay"/>
<img src="css/blue/next.png" class="next"/>
<img src="css/blue/last.png" class="last"/>
<select class="pagesize">
<option selected="selected" value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
</select>
</form>
</div>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.pager.js"></script>
<link href="css/blue/style.css" rel="stylesheet" type="text/css" />
<script>
$(function() {
$("#userlog")
.tablesorter({widthFixed: true, widgets: ['zebra']})
.tablesorterPager({container: $("#pager")});
});
</script>
and this is the page i am calling it from.
userlog.php
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuserlog.php?q="+str,true);
xmlhttp.send();
}
</script>
<div class="spacer"></div>
<div class="userlogTxt">This report shows all users who have logged in up until: <?php echo date("d/m/Y H:i:s"); ?></div>
<br />
<?php
$conn = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db("sample") or die(mysql_error());
$result2 = mysql_query('SELECT * FROM user_usr ORDER BY name_usr ASC', $conn);
echo '<select name="users" onchange="showUser(this.value)">';
echo '<option value="selected">'. 'Select a user' . '</option>';
while ($row = mysql_fetch_assoc($result2))
{
echo '<option value="'.$row['id_usr'].'">'.$row['name_usr'].'</option>';
}
echo '</select>';
?>
<br /><br />
<div id="txtHint" class="userlogTxt">Logging information will be shown here.</div></div>
#inti
it is not pulling any date from the db. just displaying header and pager.
userlog.php
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.pager.js"></script>
<link href="css/blue/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function showUser(str)
{
$.get("getuserlog.php?q="+str,function(response) {
$("#txtHint").html(response);
// Tablesorter will run, just after you loaded the ajax response
$("#userlog").tablesorter({widthFixed: true, widgets: ['zebra']})
.tablesorterPager({container: $("#pager")
});
});
}
</script>
<div class="spacer"></div>
<div class="userlogTxt">This report shows all users who have logged in up until: <?php echo date("d/m/Y H:i:s"); ?></div>
<br />
<?php
$conn = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db("sample") or die(mysql_error());
$result2 = mysql_query('SELECT * FROM user_usr ORDER BY name_usr ASC', $conn);
echo '<select name="users" onchange="showUser(this.value)">';
echo '<option value="selected">'. 'Select a user' . '</option>';
while ($row = mysql_fetch_assoc($result2))
{
echo '<option value="'.$row['id_usr'].'">'.$row['name_usr'].'</option>';
}
echo '</select>';
?>
<br /><br />
<div id="txtHint" class="userlogTxt">Logging information will be shown here.</div></div>
getuserlog.php
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sample", $con);
$sql="SELECT * FROM logger_log WHERE idusr_log = '".$q."' order by datein_log desc";
$result = mysql_query($sql);
echo "<table id=\"userlog\" class=\"tablesorter\" cellspacing=\"1\">
<thead>
<tr>
<th align=\"left\">Ip Address</th>
<th align=\"left\">Date In</th>
<th align=\"left\">Date Out</th>
</tr>
</thead>";
echo "<tbody>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ip_log'] . "</td>";
echo "<td>" . date('d/m/Y H:i:s',strtotime($row['datein_log'])) . "</td>";
echo "<td>" . date('d/m/Y H:i:s',strtotime($row['dateout_log'])) . "</td>";
echo "</tr>";
}
echo"</tbody>";
echo "</table>";
mysql_close($con);
?>
<div id="pager" class="pager">
<form>
<img src="css/blue/first.png" class="first"/>
<img src="css/blue/prev.png" class="prev"/>
<input type="text" class="pagedisplay"/>
<img src="css/blue/next.png" class="next"/>
<img src="css/blue/last.png" class="last"/>
<select class="pagesize">
<option selected="selected" value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
</select>
</form>
</div>
where have i gone wrong? thanks
I recommend you, to use the jQuery Ajax functions in userlog.php, and since the script inside getuserlog.php is constant, move it to the userlog.php, something like this:
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.pager.js"></script>
<link href="css/blue/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function showUser(str)
{
$.get("getuserlog.php?q="+str,function(response) {
$("#txtHint").html(response);
// Tablesorter will run, just after you loaded the ajax response
$("#userlog").tablesorter({widthFixed: true, widgets: ['zebra']})
.tablesorterPager({container: $("#pager")});
});
}
</script>
EDIT: Put all you javascript in the main page. The ajax response should only contain the data you want to get from the server.

Categories