I have a webpage with three radio buttons and an empty table. My goal is to select a radio button and have the table show a list of employees based on whichever radio button is clicked. Right now the list does not show up when I hit the button. I don't know what I'm doing wrong. I tried adding an alert to the doAjax function and the alert appeared so I know it's getting to that function. Below is my code, I have three files. Any help is appreciated.
//assign3.php
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src = "http://code.jquery.com/jquery-3.2.1.min.js">
</script>
<script src ="js/assign3js.js" type = "text/javascript" ></script>
</head>
<body>
<table border ='1'style = 'margin:auto' id = "employees" >
<tr><td colspan ='3'><h1>Employees </h1></td></tr>
<th> First Name</th>
<th>Last Name</th>
<th>Employee ID</th>
</table>
<input type="radio" name="employeeType" value="server" id="server"> Server<br>
<input type="radio" name="employeeType" value="bartender"id="bartender"> Bartender<br>
<input type="radio" name="employeeType" value="host"id = "hosts"> Host<br>
</body>
//script.js
$("document").ready(
function()
{
$("#server").click(doAjax);
$("#hosts").click(doAjax1);
$("#bartender").click(doAjax2);
}
);
function doAjax()
{
$.ajax({"method":"POST","url":"servers.php"}).done(update);
}
function update(data)
{
result = JSON.parse(data);
for(index =0; index < result.length; index++)
{
var row = "<tr>";
row += "<td>" + result[index].firstName + "</td>";
row += "<td>" + result[index].lastName + "</td>";
row += "<td>" + result[index].employeeID + "</td>";
row += "</tr>";
$("#employees").append(row);
}
}
//server.php
<?php
$server = (object) null;
$connection = "mysql:host=localhost;dbname=restaurant";
$user = "root";
$pwd = "mysql";
$db = new PDO($connection, $user, $pwd);
$results = $db->query("SELECT firstName, lastName, employeeID FROM
employee JOIN `server` ON employee.employeeID = server.employeeID");
while ($row = $results->fetch())
{
$server->firstName= $row["firstName"];
$server-> lastName=$row["lastName"] ;
$server->employeeId = $row["employeeID"];
}
$employee = [];
array_push($employee,$server);
$json1 = json_encode($employee);
echo $json1;
?>
My answer is just an addition to #alex's answer. Alex has very good pointed out the main problems/aspects!
I would suggest you another approach: to use only one js function for getting the employee data, no matter which radio button you are selecting. When you click on a radio button, send an ajax request with the corresponding radio button's value as argument. This value will be read on the server side and, dependent on it, a corresponding sql statement will be built and executed. The response will be read and appended to the employees table.
There would be too much to say here regarding your code version and my proposal. I hope you'll understand what I did.
Main points:
I renamed "server.php" to "get-employee.php" (it's obvious why).
I implemented the use of prepared statements instead of query, so that you are on a safe side in regard of the sql injection, in case you need to use input parameters in your queries.
The employee data is fetched from db and saved in an array by using the fetchAll() method. No need for fetching and looping through objects.
The db connection details are defined in constants.
An array with db connection options regarding exception handling and others is added now (needed).
Added the tbody container to the table, to which the employees data will be appended. In general, if you use th then use it inside a thead container. And if you use thead, then use a tbody too.
I think this is all that's important. Feel free to ask me anything... tomorrow.
Good luck further.
assign3js.js
$(document).ready(function () {
$('input[name="employeeType"]').click(function () {
var employeeType = $(this).val();
updateEmployees(employeeType);
});
});
function updateEmployees(type) {
$.ajax({
method: 'post',
dataType: 'json',
url: 'get-employee.php',
data: {
'type': type
}
})
.done(function (response, textStatus, jqXHR) {
if (response) {
for (var i = 0; i < response.length; i++) {
var row = '<tr>';
row += '<td>' + response[i].firstName + '</td>';
row += '<td>' + response[i].lastName + '</td>';
row += '<td>' + response[i].employeeID + '</td>';
row += '</tr>';
$('#employees tbody').append(row);
}
} else {
$('#employees tbody').append('<tr><td colspan="3">No employees found</td></tr>');
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
// alert(textStatus + '\n' + errorThrown + '\n\n' + jqXHR.responseText);
})
.always(function (response, textStatus, jqXHR) {
//...
});
}
assign3.php:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="js/assign3js.js" type="text/javascript"></script>
<style type="text/css">
#employees {
/*margin: auto;*/
border: 1px solid #ccc;
}
#employee-types {
margin-top: 20px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<table id="employees">
<thead>
<tr>
<th colspan="3">
<h1>Employees</h1>
</th>
</tr>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Employee ID</th>
</tr>
</thead>
<tbody></tbody>
</table>
<fieldset id="employee-types">
<legend>Employee type</legend>
<input type="radio" id="server" name="employeeType" value="server">
<label for="server">Server</label><br/>
<input type="radio" id="bartender" name="employeeType" value="bartender">
<label for="bartender">Bartender</label><br/>
<input type="radio" id="hosts" name="employeeType" value="host">
<label for="hosts">Host</label><br/>
</fieldset>
</body>
</html>
get-employee.php
<?php
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'restaurant');
define('USERNAME', 'root');
define('PASSWORD', 'mysql');
define('CHARSET', 'utf8');
// Error reporting.
error_reporting(E_ALL);
ini_set('display_errors', 1); // SET IT TO 0 ON A LIVE SERVER!
//
// Create a PDO instance as db connection to db.
$connection = new PDO(
sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s', HOST, PORT, DATABASE, CHARSET)
, USERNAME
, PASSWORD
, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);
$response = false;
if (isset($_POST['type'])) {
$employeeType = $_POST['type'];
/*
* The bindings array, mapping the named markers from the sql statement
* (if any) to the corresponding values. It will be directly passed as
* argument to the PDOStatement::execute method.
*
* #link http://php.net/manual/en/pdostatement.execute.php
*/
$bindings = [];
// Set the sql statement based on the submitted employee type.
switch ($employeeType) {
case 'bartender':
// $sql = '...';
// $bindings[:markerName] = markerValue;
break;
case 'hosts':
// $sql = '...';
// $bindings[:markerName] = markerValue;
break;
case 'server':
default:
$sql = 'SELECT
emp.firstName,
emp.lastName,
emp.employeeID
FROM employee AS emp
JOIN `server` AS srv ON srv.employeeID = emp.employeeID';
break;
}
// Prepare the sql statement for execution and return a statement object.
$statement = $connection->prepare($sql);
// Execute the prepared statement.
$statement->execute($bindings);
// Fetch data - all at once - and save it into response array.
$response = $statement->fetchAll(PDO::FETCH_ASSOC);
//-----------------------------------------------------------------------
// ...or fetch data one record at a time and save it into response array.
//-----------------------------------------------------------------------
// $employee = [];
// while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
// $employee[] = $row;
// }
// $response = $employee;
//-----------------------------------------------------------------------
}
echo json_encode($response);
Your SQL query is wrong, you have it doing
SELECT firstName, lastName, employeeID FROM employee JOIN `server` ON
employee.employeeID = server.employeeID
but employeeID exists in both employee and server so you need to modify your query to specific which table to get employeeID from so it should look like
SELECT employee.firstName, employee.lastName, employee.employeeID FROM employee JOIN `server` ON
employee.employeeID = server.employeeID
I made an SQLFiddle here which shows this. You should check if $results equals false, because the query function will return false if it fails.
That worked for me, I had to change line 14 in server.php as well or else it wouldn't display the employee ID, this was because in the ajax script you reference it as employeeID but you set it as employeeId on line 14 so it would now be
$server->employeeID = $row["employeeID"];
Now when you run all of it will only one employee, if you want it to return multiple you need to have an array in server.php that you push employees to because right now it will overwrite the previous employee and only return the last one because of them writing to the same object with the same keys.
For multiple employees to return I changed the code to
...
$server = [];
...
$count = 0;
while ($row = $results->fetch()) {
//create new class to stop warnings of creating object from empty value
$server[$count] = new \stdClass();
$server[$count]->firstName= $row["firstName"];
$server[$count]->lastName=$row["lastName"] ;
$server[$count]->employeeID = $row["employeeID"];
$count++;
}
...
what this does is $server is now an array, and every time we loop over an employee in the while loop we assign our values to a new object stored in $server's array.
and the script.js looked like this
function update(data) {
var result = JSON.parse(data)[0]; // [0] because the json was wrapped in
// double []'s
for(var index =0; index < result.length; index++) {
var row = "<tr>";
row += "<td>" + result[index].firstName + "</td>";
row += "<td>" + result[index].lastName + "</td>";
row += "<td>" + result[index].employeeID + "</td>";
row += "</tr>";
$("#employees").append(row);
}
}
Not sure if any of this is the best solution to the problem, but I got it to work without too much trouble.
Related
I have a table pulling info from a database with the last column of each row being an input tag labeled COMPLETE a user can click on. I want to be able to click on the tag and have it update my database to change a boolean field which would change COMPLETE from 0 to 1. Right now, I can't seem to update the rows if I click on them out of order. so If i click to update the first row and then click a few rows below, it will update the second row. It will update any row you want if you click the button for that row twice, but first it updates the row where you left off previously...
<form action='' method='POST'>
<?php
$current_date = date("Y-m-d");
$n = 1;
$sql = "SELECT id, date, pname, details, time, tech FROM task WHERE task='LAB' AND complete=0 ORDER BY date DESC";
$result = $link->query($sql);
echo $current_date;
echo "<table>
<tr>
<th>Date</th>
<th>Project</th>
<th>Details</th>
<th>Start Time</th>
<th>Technician</th>
</tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr align='center'><td>" .$row["date"]. "</td><td>" .$row["pname"]. "</td><td>"
.$row["details"]. "</td><td>" .$row["time"]. "</td><td>" .$row["tech"]. "</td>
<td><input type='submit' name=".$n." value='Complete' /></td></tr>";
if (isset($_POST[$n])) {
$id = $row["id"];
$update = "UPDATE task SET complete = 1 WHERE task='LAB' AND id = ".$id."";
echo $update;
$update_result = $link->query($update);
}
$n++;
}
echo "</table>";
$link->close();
?>
</form>
One of the things I noticed was you don't do proper concatenation.
ANSWER:
You can try putting form for each row, then use hidden input field for storing the id:
while ($row = $result->fetch_assoc()) {
echo '<tr align="center">
<td>'.$row["date"].'</td>
<td>'.$row["pname"].'</td>
<td>'.$row["details"].'</td>
<td>'.$row["time"].'</td>
<td>'.$row["tech"].'</td>
<td>
<form action="" method="POST">
<input type="hidden" name="id" value="'.$row["id"].'">
<input type="submit" name="complete" value="Complete"/>
</form>
</td>
</tr>';
}
You can then process the form:
if(isset($_POST["complete"])) {
$id = $_POST["id"];
$stmt = $link->prepare("UPDATE task SET complete = 1 WHERE task='LAB' AND id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
}
Second Option:
You can try using Ajax for seamless transaction:
while ($row = $result->fetch_assoc()) {
echo '<tr align="center">
<td>'.$row["date"].'</td>
<td>'.$row["pname"].'</td>
<td>'.$row["details"].'</td>
<td>'.$row["time"].'</td>
<td>'.$row["tech"].'</td>
<td>
Complete
</td>
</tr>';
}
Then create your script (I'll be using jQuery for this example). You may include this at the bottom of your main file:
<script>
$(document).ready(function(){ /* PREPARE THE SCRIPT */
$(".btn").click(function(){ /* WHEN COMPLETE BUTTON IS CLICKED */
var elem = $(this),
id = elem.attr('data-artid'); /* GET THE ID OF THE CLICKED ELEMENT */
$.ajax({ /* PROCESS AJAX */
url: "process.php", /* THE FILE WHERE THE FORM WILL BE PROCESSED */
type: "POST", /* METHOD TO BE USED */
data: {"id":id}, /* THE DATA TO BE PASSED TO process.php */
dataType: 'json', /* TYPE OF DATA TO BE RETURNED */
success: function(result){ /* IF process.php IS SUCCESSFUL */
if(result.boolean){
elem.closest('tr').remove(); /* REMOVE THE ENTIRE ROW */
}
}
});
return false; /* THIS WILL PREVENT FROM SCROLLING TO THE TOP OF THE PAGE */
});
});
</script>
Then process the form in process.php (separate file):
/** INCLUDE HERE SOMEWHERE YOUR DATABASE CONNECTION **/
$boolean = false; /** DEFAULT VALUE TO BE RETURNED **/
if(!empty($_POST["id"])){
$id = $_POST["id"];
$stmt = $link->prepare("UPDATE task SET complete = 1 WHERE task='LAB' AND id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
$boolean = true;
}
echo json_encode(array('boolean' => $boolean)); /* THIS WILL BE RETURNED TO THE AJAX REQUEST */
This question already has answers here:
jquery serialize and multi select dropdown
(6 answers)
Get the values of 2 HTML input tags having the same name using PHP
(4 answers)
Closed 6 years ago.
I want to change the status in the database, with a select dropdown field.
I am sending with ajax. The first row is always working, but with multiple data i cant update the second, third..etc
I tried with serialize(), but its not working.
select from database:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".allbooks").change(function(){
var allbooks = $(this).val();
var dataString = "allbooks="+allbooks;
$.ajax({
type: "POST",
data: dataString,
url: "get-data.php",
success: function(result){
$("#show").html(result);
}
});
});
});
</script>
</head>
<body>
<?php
define("HOST","localhost");
define("USER","root");
define("PASSWORD","");
define("DATABASE","hotel");
$euConn = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
$selectRooms = "SELECT * FROM proba WHERE status='inRoom'";
$resultRooms = mysqli_query($euConn,$selectRooms);
if (mysqli_num_rows($resultRooms) > 0) {
echo "<div id='reserved' align='center'>";
While ($row = mysqli_fetch_array($resultRooms)) {
echo $row[1];
echo $row[0];
?>
<select name="allbooks" id="allbooks">
<option name="years">Choose</option>
<?php
for($i=1; $i<=19; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select><br />
<?php }
}
else
echo "<h4>nothing in the db</h4></div>";
?>
<div id="show">
</div>
</body>
</html>
and getting the results:
if(!empty($_POST["allbooks"])) {
var_dump($_POST);
$id = 2;
//echo $_POST['modelS'];
$room = $_POST['allbooks'];
$sql2 = "UPDATE proba SET room='$room' WHERE id_reservation='$id'";
$query = mysqli_query($euConn, $sql2);
var_dump($query);
}
How to change, or what would be a simple solution? Thanks for the help.
You have multiple select elements on the rendered page with the id allbooks That's wrong, IDs must be unique. You'll want to change those to a class and use $(".allbooks").change(function(){ ....
As far as sending the row id to the server with the update, you'll need to first add the row id to the select box so you can retrieve it later, something like '<select name="allbooks" class="allbooks" data-row-id="' . $row['id_reservation'] . '"> would work.
I would also recommend splitting the work up into several functions to better organize your code (classes would be even better)
It's hard to test without access to the DB, but this should do it for you. Note that I have the update function on the same page and updated the ajax url property to '' which will send the data to a new instance of the current page to handle the update.
<?php
require_once ("db_config.php");
function updateRoom($euConn, $newRoomVal, $id)
{
$stmt = $euConn->prepare("UPDATE proba SET room=? WHERE id_reservation=?");
$stmt->bind_param('ii', $newRoomVal, $id);
/* execute prepared statement */
$stmt->execute();
/* close statement and connection */
$affectedRows = mysqli_stmt_affected_rows($stmt) > 0;
$stmt->close();
return $affectedRows;
}
function getRooms($euConn)
{
$selectRooms = "SELECT * FROM proba WHERE status='inRoom'";
$resultRooms = mysqli_query($euConn,$selectRooms);
$rows = mysqli_fetch_all($resultRooms,MYSQLI_ASSOC);
return count($rows) < 1 ? '<h4>nothing in the db</h4></div>' : createSections($rows);
}
function createSections($rows)
{
$sections = [];
foreach( $rows as $row){
$options = [];
for ($i = 1; $i <= 19; $i++)
$options[] = "<option value=" . $i . ">" . $i . "</option>";
$options = implode('', $options);
$select = '<select name="allbooks" class="allbooks" data-row-id="' . $row['id_reservation'] . '"><option value="">Choose</option>' . $options . '</select><br/>';
// .. build all your other row elements here....
$section = 'some other compiled html'.$select;
$sections[]=$section;
}
return implode('', $sections);
}
$euConn = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
if(isset($_POST["allbooks"]) && $_POST["allbooks"] !='') {
$updated = updateRoom($euConn,$_POST["allbooks"],$_POST["rowId"] );
echo json_encode(['success'=>$updated]);
exit;
}
$pageSections = getRooms($euConn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".allbooks").change(function(){
var $this = $(this);
var allbooks = $this.val();
var rowId = $this.data('row-id');
var dataString = "allbooks="+allbooks+'&rowId='+rowId;
$.ajax({
type: "POST",
data: dataString,
url: "",
success: function(result){
$("#show").html(result);
}
});
});
});
</script>
</head>
<body>
<div id='reserved' align='center'>
<?php echo $pageSections ?>
<div id="show">
</div>
</body>
</html>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How to display data from database by user specified date range and also comparing user input value with database field value.
The query is like this:
$sql = "SELECT * FROM table WHERE date between '".$date_min"' AND '".date_max"'";
assuming $date_min and $date_max are the values of your user input, and table the DB table where you want to query.
The php will be something like:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM table WHERE date between '".$date_min"' AND '".date_max"'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
Provided you made the part for user input.
These is from http://www.w3schools.com/php/php_mysql_select.asp.
Some research before making a question is required.
Regards
Now, you could try something like this, using an ajax request (jQuery required):
JS:
/**
* Created by evochrome on 26-3-2016.
*/
$( document ).ready(function() {
var timer;
$('#reset').click(function(e) {
$('input').val(""); //set value equal to zero
});
$('input').on("input", function (e) {
clearInterval(timer);
timer = setTimeout(getTableContents,2000);//Execute function `getTableContents` after 3s
});
});
function getTableContents() {
$('td').fadeOut(500, function(){ $(this).parent().remove();});
setTimeout(function() {
var inputs = {};
$(".theader input").each(function () {
if ($(this).val() != '') {
inputs[$(this).attr('name')] = $(this).val();
}
});
$.ajax({ //ajax request
method: "POST",
url: "../php/fetch.php",
data: inputs,
dataType: 'json',
cache: false,
success: function (data) {
var tmpObject = {};
var i = 0;
data.forEach(function (row) {
var obj = data[i];
$('table').append("<tr id='t" + i + "'></tr>");
Object.keys(obj).forEach(function (key) {
$('#t' + i).append("<td style='display: none;'>" + row[key] + "</td>");
});
i++
});
$('td').fadeIn(500);
}
})
}, 500);
}
CSS:
table {
width: 80%;
}
td {
width: 40%;
background-color:green;
height: 40px;
text-align: center;
}
.theader{
width:100%;
justify-content:space-around;
display:flex;
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>T-Test</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Input Some Data</h1>
<div class="theader">
<input name="FromDate" type="date"/>
<input name="ToDate" type="date"/>
<button id="reset">Reset</button>
</div>
<table>
<tr>
<td>2</td>
<td>John</td>
<td>Appleseed</td>
</tr>
</table>
<script src="js/jquery-2.2.0.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
PHP:
<?php
/**
* Creator: evochrome
* Date: 26-3-2016
* Time: 15:40
*/
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', '1');
$conn = new mysqli('localhost', $db_name, $db_password, $db_user);
if (! $conn){
echo 'Oh damn a crash!';
die(' Connection failed :(');
}
$fields = array(
'FromDate', 'ToDate'
);
$where = "1=1"; //true
foreach ($fields as $field) {
if ($value = $_POST[$field]) {
$where .= " AND $field = '$value'"; //for each field add clause
}
}
$query = $conn->query("SELECT * FROM $table_name WHERE $where"); //insert tablename and where clause
$array = array();
while($row = $query->fetch_assoc()){ //fetch from db
$array[] = $row;
}
echo json_encode($array);
$query->close();
$conn->close();
I have a webpage http://skywateryachts.com/disp_new.php where I formatted the currency with no problem.
However, the sorting of the listed price appears to be by order of the first several digits rather than total value. Example, $110,000 appears before $110,900,000 when sorted descending.
The MySQL field type is INT and I just formatted the SELECT statement for the currency symbol.
I'm using the dataviewer extension in the WYSISWYG Webbuilder and custom formatting the code. But I am new to customizing MySQL.
I'm thinking it would be better to eliminate the sort feature and do it myself but would like first to know what the issue could be with the sorting of the digits.
Thanks
Pertinent code:
<script type="text/javascript">
$(document).ready(function()
{
$.fn.alternateRowColors = function()
{
$('tbody tr:odd', this).removeClass('even').addClass('odd');
$('tbody tr:even', this).removeClass('odd').addClass('even');
return this;
};
$('table.sortable').each(function()
{
var $dataviewer = $(this);
$dataviewer.alternateRowColors();
$('th', $dataviewer).each(function(column)
{
var $header = $(this);
var findSortKey;
findSortKey = function($cell)
{
return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();
};
if (findSortKey)
{
$header.addClass('clickable').hover(function()
{
$header.addClass('hover');
}, function()
{
$header.removeClass('hover');
}).click(function()
{
var sortDirection = 1;
if ($header.is('.sorted-asc'))
{
sortDirection = -1;
}
var rows = $dataviewer.find('tbody > tr').get();
$.each(rows, function(index, row)
{
var $cell = $(row).children('td').eq(column);
row.sortKey = findSortKey($cell);
});
rows.sort(function(a, b)
{
if (a.sortKey < b.sortKey) return -sortDirection;
if (a.sortKey > b.sortKey) return sortDirection;
return 0;
});
$.each(rows, function(index, row)
{
$dataviewer.children('tbody').append(row);
row.sortKey = null;
});
$dataviewer.find('th').removeClass('sorted-asc').removeClass('sorted-desc');
if (sortDirection == 1)
{
$header.addClass('sorted-asc');
}
else
{
$header.addClass('sorted-desc');
}
$dataviewer.find('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted');
$dataviewer.alternateRowColors();
});
}
});
});
<div id="dataviewer" style="position:absolute;overflow:auto;left:269px;top:390px;width:803px;height:980px;z-index:46">
<?php
$mysql_host = 'localhost';
$mysql_user = 'xxxx';
$mysql_password = 'xxxx';
$mysql_database = 'xxxx';
$mysql_table = 'boats';
$db = mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_select_db($mysql_database, $db);
$sql = "SELECT Date_Listed, Est_DOM, LOA, Builder, Built, Currency, concat('$', format(Listing_Price, 0)), NFS_USA FROM ".$mysql_table;
$result = mysql_query($sql, $db);
?>
<table cellpadding="0" cellspacing="1" width="100%" class="sortable paginated">
<thead>
<tr>
<th>List Date</th>
<th> Est DOM</th>
<th> Length</th>
<th> Builder</th>
<th> Year Built</th>
<th> Currency</th>
<th> Listing Price</th>
<th> NFS USA</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_row($result))
{
echo " <tr>\n";
foreach ($row as $cell)
{
echo " <td>" . $cell . "</td>\n";
}
echo " </tr>\n";
}
?>
</tbody>
</table>
</div>
You probably are sorting by your formatted column in the field list of your SELECT. Instead, in your ORDER BY reference the name of the integer column directly from your table.
So if you have this:
SELECT FORMAT(foo, '$99,999,999.99')
FROM bar
ORDER BY 1
instead do this
SELECT FORMAT(foo, '$99,999,999.99')
FROM bar
ORDER BY foo
(Ignore the actual syntax of the formatting - I always have to look that stuff up to get the right function and syntax and I'm just doing it for an example.)
Inside my page I have an input ("Model") with a datalist attribute and a select menu ("Brand"). When a user select one of the options of the datalist from the Model, it will dynamically change the options value from the Brand select menu. Both options value from Model and Brand are called from the database. This is what I code so far;
<input type="text" name="type" id="type" list="datalist1" onchange="fw();"/>
<datalist id="datalist1">
<?php
$query9 = "SELECT DISTINCT model FROM server ORDER BY model ASC";
$result9 = mysql_query($query9);
while($row9 = mysql_fetch_assoc($result9))
{
echo '<option value="'.$row9['model'].'">';
} ?>
</datalist>
<select name="brand" id="test2"><option value="">-- Select Brand--</option></select>
Script;
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function fw()
{
var selname = $("#type").val();
$.ajax({ url: "getBrand.php",
data: {"brand":brand},
type: 'post',
success: function(output) {
document.getElementById('test2').options.length = 0;
document.getElementById('test2').options[0]=new Option(output,output);
// document.getElementById('test2').options[1]=new Option(output,output);
}
});
}
</script>
getBrand.php
<?php
define('DB_HOST1', 'localhost');
define('DB_NAME1', 'standby');
define('DB_USER1', 'root');
define('DB_PASS1', '');
$link = mysql_connect(DB_HOST1, DB_USER1, DB_PASS1);
if(!$link)
{
exit('Cannot connect to server "' . DB_HOST1 . '"');
}
mysql_select_db(DB_NAME1, $link) or die('Cannot use database "' . DB_NAME1 . '"');
if (isset($_POST['brand'])) {
$selname = $_POST['brand'];
$query = "SELECT * FROM server WHERE model='$brand'";
$res = mysql_query($query);
$aBrand= array();
while($rows = mysql_fetch_assoc($res)) {
$brand= $rows['brand'];
$aBrand[] = $brand;
echo $aBrand[0];
echo $aBrand[1];
}
} ?>
From what I have coded, I have succesfully change the select menu dynamically but there is one problem. When there is more one data is called from getBrand.php, the 'output' in the select menu will combine all of the data into one line. For example, if the data is "M3000" and "M4000", it will display as "M3000M4000". Now, how do I split it and make it as a normal select options?
I'm still learning Javascript and I hope anyone here can guide me.
NOTE : The code only works in Firefox because of the datalist attribute
Send your data from getBrand.php as
echo implode(";", $aBrand);
this will generate a string like M3000;M4000;M5000;M6000
and in your java script code break the string into array using this code.
StrArr = Str.split (";");
here 'Str' is your output given by getBrand.php, and 'StrArr' is the array which contains your brands.
add a special character in the string returned form php
PHP
elementcount=0;
while($row9 = mysql_fetch_assoc($result9))
{
if(elementcount>0)
echo '$<option value="'.$row9['model'].'">';//place a $ sign in start or you can for any special character
else
echo '<option value="'.$row9['model'].'">';
}
now in javascript
success: function(output) {
output = output.split("$");
document.getElementById('test2').options.length = 0;
//here now loop through the elements and add
for(var i=0,i<output.length-1)
document.getElementById('test2').options[0]=new Option(output[i],output[i]);
// document.getElementById('test2').options[1]=new Option(output,output);
}