Html Dropdown Menu Displays nothing - javascript

I'm trying to diplay my table when I click a value in Dropdown list. When I view page code source, the table values are there but it's not showing. I would like to query from mysql using the value from dropdown and populate the table with datas from mysql query.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript">
function jsFunction(value){
<?php
$con=mysqli_connect("localhost","root","","dengue");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM mapping_details where case_type='value'";
echo '<div class="table-responsive ">
<table class="table table-condensed table-hover table-bordered">
<thead>
<tr>
<th>Barangay</th>
<th>Case Type</th>
<th>Total Dengue Cases</th>
</tr>
</thead>
<tbody>';
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['brgy'] . "</td>";
echo "<td>" . $row['case_type'] . "</td>";
echo "<td>" . $row['total_case_brgy'] . "</td>";
echo "</tr>";
}
echo '</tbody></table></div>';
mysqli_close($con);
?>
}
</script>
</head>
<body>
<select id ="ddl" name="ddl" onchange="jsFunction(this.value);">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
</body>
</html>
Originally, in my other webpages, the php code is inside the body. But this time, I can't make it work if I use dropdown menu so that's why I put it inside the function for me to be able to use onchange function. I've read some answers using AJAX or JSON but I'm not familiar with those so if possible I only want to use javascript as maybe it is the simplest way.

What you are trying to do here is run PHP code in the browser, which you cannot do. All the HTML, CSS, and JavaScript is sent down to the client ( your browser ) and then is rendered and initialized by the browser. When you are calling your onchange event to call the jsFunction() you are trying to execute PHP within that function but- you are on the client-side running in chrome or firefox or some browser and you cannot execute PHP there. PHP has to run on page load and then can change the html, css, or JavaScript before it is sent down to the client.
There are two ways of doing what you want to do. You can send an Ajax request ( call your server using javascript ) to get new data or you can submit a form that reloads the page and you can run PHP like you are comfortable with- modifying the html, css, and/or javascript before it is returned to the client (browser).
Here is the non-ajax way which just keeps reloading the page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<?php
$value = isset( $_POST['ddl'] ) ? $_POST['dll'] : 1; // we are setting 1 as the default
$con=mysqli_connect("localhost","root","","dengue");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM mapping_details where case_type='{$value}'";
$html= '<div class="table-responsive ">
<table class="table table-condensed table-hover table-bordered">
<thead>
<tr>
<th>Barangay</th>
<th>Case Type</th>
<th>Total Dengue Cases</th>
</tr>
</thead>
<tbody>';
while($row = mysqli_fetch_array($result))
{
$html.= "<tr>";
$html.= "<td>" . $row['brgy'] . "</td>";
$html.= "<td>" . $row['case_type'] . "</td>";
$html.= "<td>" . $row['total_case_brgy'] . "</td>";
$html.= "</tr>";
}
$html.= '</tbody></table></div>';
mysqli_close($con);
?>
}
</script>
</head>
<body>
<form method="POST" action="">
<select id="ddl" name="ddl">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
</form>
<script>
$("select#ddl").on("change",function(){
$('form').submit();
});
</script>
<?php echo $html; ?>
</body>
</html>

Related

How to get unique button id from a while loop? (PHP)

First of all here's my code:
session_start();
require_once "config.php";
$email = $_SESSION["email"];
$result = mysqli_query($link,"SELECT * FROM cuponai WHERE gmail='$email' AND panaudoti=0");
echo "<table border='1'>
<tr>
<th>Cupono kodas</th>
<th>Apply code</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr> ";
echo "<td>" . $row['cuponas'] . "</td>";
echo "<td> <form method='post'><input type='submit' name='". $row['cuponas'] ."' value='submit'></from></td>";
echo "</tr>";
}
echo "</table>";
if(isset($_POST['???????'])) {
$sql = "UPDATE cuponai SET panaudoti=1 WHERE cuponas='????????????' ";
if ($link->query($sql) === TRUE) {
echo "YOU DID IT WOO";
} else {
echo "Error updating record: " . $link->error;
}
}
mysqli_close($link);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
</body>
</html>
The parts in question marks is where I'm strugling...
Basically I'm making this site where you can see your purchased coupons and each of the coupons have an apply button near them so you basically have a list and need to apply them after you apply them I want it too refresh the page and applied coupons dissapear and are marked as used in the database. But I've been scratching my head this whole time and trying to make the buttons unique with javascirpt and all that but to no avail hopefully some of you could figure out a solution here?
-sorry for the spaggeti code
In the case of the code you provided, you could add hidden input elements in your forms.
Use the same name and set the value to the unique id you want. This input's value and name will be sent to the PHP portion of your file where you can access it inside the $_POST array like so; $_POST['name_of_input']
In short, you would have to make the following adjustments to your code to make it work as you expect;
Change this
echo "<td> <form method='post'><input type='submit' name='". $row['cuponas'] ."' value='submit'></from></td>";
To this
echo "<td> <form method='post'><input type='hidden' name='couponid' value='". $row['cuponas'] ."'><input type='submit' name='". $row['cuponas'] ."' value='submit'></from></td>";
And then change this
if(isset($_POST['???????'])) {
$sql = "UPDATE cuponai SET panaudoti=1 WHERE cuponas='????????????' ";
To this
if(isset($_POST['couponid'])) {
$sql = "UPDATE cuponai SET panaudoti=1 WHERE cuponas='".$_POST['couponid']."' ";
Your $_POST['couponid'] will hold the data of $row['cuponas'] and your code should work as you expect.
A couple of extra notes beyond the scope of the question;
1. You are currently echoing the HTML you create in PHP before the <!DOCTYPE html> tag.
Although a browser will correct for this, this isn't proper HTML form.
Rather than echoing everything at the top of the document, you might want to store it in a variable and echo that inside the <body> tag instead.
Instead of this;
echo "<table border='1'>
<tr>
<th>Cupono kodas</th>
<th>Apply code</th>
</tr>";
You could use;
$html_to_echo = "<table border='1'>
<tr>
<th>Cupono kodas</th>
<th>Apply code</th>
</tr>";
To add to this variable you can use something like this;
$html_to_echo .= "<tr> ";
And then in the HTML portion of your page;
<body>
<?php echo $html_to_echo; ?>
</body>
It is possible to interweave PHP and HTML like this in a PHP document.
2. Although already mentioned in the comments of your question, here's an extra SQL Injection warning for people passing through in the future.
Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough

How to remove dropdown duplicate

I am fairly new to the PHP PDO world, I already know now, that the connection to the DB should be in another PHP file, but then the rest does not work :(. I have tried all day, I know I am so tired of it that I have to ask here. How do I get rid of the Duplicate? I think the duplicate is there as a result of the DB connection being in the same folder, as it is not localhost but a website. So how do I write the files out in multiple files?
In the Display.php file, I have the dropdown with HTML, followed by javascript that should trigger the table when a value from the dropdown has been chosen. Action.php is where the table is created and I tried to create a separate file for the DB connection, but then I can't concatenate the "uid" javascript value to the Action.php file.
I hoped you could help me get rid of the Duplicate of the dropdown.
Tell me if I can add more info to help.
Best regards
This I an image of the duplicate when I choose a value from the dropdown, it duplicates the dropdown, and add it below. It is meant to only show the table below.
Display.php
<?php
ini_set("display_errors", "On");
error_reporting(E_ALL);
$host='database.*****.us-east.rds.amazonaws.com';
$db = '*****';
$port = 5432;
$username = '*****';
$password = '*****';
try {
$conn = new PDO("pgsql:host=$host;port=$port;dbname=$db;user=$username;password=$password");
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$sql ="select * from public.category";
//Prepare the select statement.
$stmt = $conn->prepare($sql);
//Execute the statement.
$stmt->execute();
//Retrieve the rows using fetchAll.
$users = $stmt->fetchAll();
?>
// show menu dropdown
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="margin-top: 50px;">
<h2 class="text-center">Væg en kategori </h2>
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4" style="margin-top:20px; margin-bottom:20px;">
<form id="submitForm">
<div class="form-group">
<select class="form-control Investment" name="Investment" id="Investment">
<option value="">Vælg Kategori</option>
<?php foreach($users as $user): ?>
<option value="<?= $user['id']; ?>"><?= $user['name']; ?></option>
<?php endforeach; ?>
</select>
</div>
</form>
</div>
</div>
<div class="col-md-12">
<div id="show-invest">
</div>
</div>
</div>
</body>
</html>
<!---jQuery ajax load rcords using select box --->
<script type="text/javascript">
$(document).ready(function(){
$(".Investment").on("change", function(){
var InvestmentName = $(this).val();
if (InvestmentName !== "") {
$.ajax({
url : "Action.php",
type:"POST",
cache:false,
data:{InvestmentName:InvestmentName},
success:function(data){
$("#show-invest").html(data);
}
});
}else{
$("#show-invest").html(" ");
}
})
});
</script>
Action.php
<?php
// include database connection file
include_once "testSide.php";
// include_once "DBController.php";
if(isset($_POST['InvestmentName']))
{
$uid = $_POST['InvestmentName'];
}
// load records using select box jquery ajax in PHP
$qu = "select Prod.tocon as name, one.con as yield_one, five.con as yield_two, ten.con as yield_three, twenty.con as yield_four, one.st as st_one, five.st as st_two, ten.st as st_three, twenty.st as st_four, one.top as top_one, five.top as top_two, ten.top as top_three, twenty.top as top_four;";
$result = $conn->query($qu);
if (!$result) {
trigger_error('Invalid query:' . $conn->error);
}
$output = '';
if ($result->rowCount() > 0) {
$output .= "<table class='table table-hover table-border'>
<thead>
<tr>
<th>Name</th>
<th>Afkast sidste år</th>
<th>Genst sidste 5 år</th>
<th>Genst stidste 10 år</th>
<th>Genst sidste 20 år</th>
<th>SR sidste år</th>
<th>SR 5 år</th>
<th>SR 10 år</th>
<th>SR 20 år</th>
<th>DD sidste år</th>
<th>DD 5 år</th>
<th>DD 10 år</th>
<th>DD 20 år</th>
</tr>
</thead>";
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$output .= "<tbody>
<tr>
<td>{$row["name"]}</td>
<td>{$row["yield_one"]}</td>
<td>{$row["yield_two"]}</td>
<td>{$row["yield_three"]}</td>
<td>{$row["yield_four"]}</td>
<td>{$row["st_one"]}</td>
<td>{$row["st_two"]}</td>
<td>{$row["st_three"]}</td>
<td>{$row["st_four"]}</td>
<td>{$row["top_one"]}</td>
<td>{$row["top_two"]}</td>
<td>{$row["top_three"]}</td>
<td>{$row["top_four"]}</td>
</tr>";
}
"</tbody>";
$output .= "</tbody></table>";
echo $output;
}else{
echo "No records found";
}
?>
I fixed it by moving the database connector in an isolated file. So it did not call it self in the same PHP file. Now i then call the DB from the other files with include_once

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.

Javascript MYSQL Dropdown

Apologies in advance if a) this question has already been answered, I did search but am not able to use the answers I've found and b) I am not the a very skilled programmer and am trying to learn...
To make this as short as possible...
I have a fully functioning site with a searchable and sortable database (that a co-worker pretty much build for me a long time ago, hence why I am extra confused)
I would like to add a dropdown filter that populates from the database
The code references javascript and PHP. From what I understand, the PHP populates the table data for me and the javascript triggers the 'show xx entries' filter and the search box - which are both awesome
My issue is I cannot get any code for the dropdown I would like to add to work. I can get the dropdown to populate but not actually filter the data :(
<?php
$dbhost = 'localhost';
$dbuser = 'database';
$dbpass = 'password;
$dbname = 'marchmadness';
$table = 'leaderboard';
//connect to the database
$db = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Leaderboard</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="icon" type="image/png" href="/favicon.ico" />
<link rel="stylesheet" type="text/css" href="assets/css/main.css">
<link rel="stylesheet" type="text/css" href="assets/css/listing.css" media="all" />
<script type="text/javascript" src="assets/js/jquery.min.js"></script>
<script type="text/javascript" language="javascript" src="assets/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
/* This triggers the cool filtering stuff, without this it's just a normal table of data */
$('table').dataTable({
"iDisplayLength": 10
});
});
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
</script>
</head>
<body id="listing">
<div id="wrapper">
<div id="topbox" align="center">
<img src="_Images/maddnessheader.png" width="539" height="296" align="center" /></div>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<?
$sql="SELECT Title FROM leaderboard";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["leaderboard"];
$thing=$row["Title"];
$options.="<OPTION VALUE=\"$id\">".$thing.'</option>';
}
?>
<SELECT NAME=thing>
<OPTION VALUE=0>Choose
<?=$options?>
</SELEC
T>
<table align="center">
<thead>
<tr>
<th>Title</th>
<th>Name</th>
<th>Call Coding (%)</th>
<th>FizzBack SAT Score (%)</th>
</tr>
</thead>
<tbody>
<?php
//get the information from the database
$result = mysql_query("SELECT * FROM `$table`;") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo '<tr>';
// print out the data from the database. Notice how the text inside $row[] matches up with the headers in phpmyadmin
echo '<td>' . htmlentities($row['Title']) . '</td>';
echo '<td>' . htmlentities($row['Name']) . '</td>';
echo '<td>' . htmlentities($row['CC']) . '</td>';
echo '<td>' . htmlentities($row['FZB']) . '</td>';
echo "</tr>\n";
}
?>
</tbody>
</table>
</div>
</body>
</html>
I think I would have to manipulate the javascript to add what I need, as that's where the the working dropdown and search box come from... but I suck a javascript :-\ If anyone could help I would REALLY appreciate it. I can share the existing Java as well if needed :D
Cheers!
Give this a try, Ive edited a few things which didn't seem quite right and added some code which should hopefully filter stuff. Bit of a guess as I've never used datatables and I dont know what the datatypes are.
<?php
$dbhost = 'localhost';
$dbuser = 'database';
$dbpass = 'password';
$dbname = 'marchmadness';
$table = 'leaderboard';
//connect to the database
$db = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
?>
<!doctype html>
<html lang="en">
<head>
<title>Leaderboard</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="icon" type="image/png" href="/favicon.ico" />
<link rel="stylesheet" type="text/css" href="assets/css/main.css">
<link rel="stylesheet" type="text/css" href="assets/css/listing.css" media="all" />
<script type="text/javascript" src="assets/js/jquery.min.js"></script>
<script type="text/javascript" language="javascript" src="assets/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
var table; // used to store a reference later
$.fn.dataTablesExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
if (aData[0].toLowerCase() == $('#title_filter').val().toLowerCase()) {
return true;
} else {
return false;
}
}
);
$(document).ready(function() {
/* This triggers the cool filtering stuff, without this it's just a normal table of data */
table = $('table').dataTable({ "iDisplayLength": 10 }); // this starts the datatable stuff and returns a reference to it
});
$("#title_filter").onchange(function() {
table.fnDraw(); // forgot this line - whoops
});
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
</script>
</head>
<body id="listing">
<div id="wrapper">
<div id="topbox" align="center">
<img src="_Images/maddnessheader.png" width="539" height="296" align="center" /></div>
<?php
$sql="SELECT Title FROM leaderboard";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["leaderboard"];
$thing=$row["Title"];
$options.="<option value=\"$thing\">".$thing.'</option>';
}
?>
<select id="title_filter">
<?=$options?>
</select>
<table align="center">
<thead>
<tr>
<th>Title</th>
<th>Name</th>
<th>Call Coding (%)</th>
<th>FizzBack SAT Score (%)</th>
</tr>
</thead>
<tbody>
<?php
//get the information from the database
$result = mysql_query("SELECT * FROM `$table`;") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo '<tr>';
// print out the data from the database. Notice how the text inside $row[] matches up with the headers in phpmyadmin
echo '<td>' . htmlentities($row['Title']) . '</td>';
echo '<td>' . htmlentities($row['Name']) . '</td>';
echo '<td>' . htmlentities($row['CC']) . '</td>';
echo '<td>' . htmlentities($row['FZB']) . '</td>';
echo "</tr>\n";
}
?>
</tbody>
</table>
</div>
</body>
</html>

Display data fetched from remote PHP (mysql) in html table [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I have a PHP page displaying data from a mysql database, based on a dropdown list selection, also from a mysql database. This obviously makes use of a JavaScript.
The PHP and mysql integration is working perfectly however I need to change the way the data is displayed.
Currently the returned mysql data is displaying in one table cell, I want each returned mysql field to be displayed in its own table cell.
I have added a photo of the output, I want it to display in each table cell, not in one.
I have attached the code from both my PHP file and the PHP file querying the database.
Any assistance would be greatly appreciated!
index.php
<html>
<head>
<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","getdata.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$con = mysql_connect('localhost', 'unilever_root', 'Unilever2011');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("unilever_unilever", $con);
$skusql="SELECT packcode from skudata";
$resultsku=mysql_query($skusql);
$optionssku="";
while ($row=mysql_fetch_array($resultsku))
{
$sku=$row["packcode"];
$optionssku.="<OPTION VALUE=\"$sku\">".$sku;
}
?>
<table border=1>
<tr>
<td>SKU</td>
<td>Description</td>
<td>SU</td>
<td>Points</td>
<td>Category</td>
<td>Grouping</td>
</tr>
<tr>
<td>
<select name="users" onchange="showUser(this.value)">
<OPTION VALUE=0>
<?=$optionssku?>
</SELECT>
</td>
<td>
<div id="txtHint"><b>SKU Details will be seen here</b></div>
</td>
</tr>
</table>
</body>
</html>
getdata page
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'dbuser', 'password');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("unilever_unilever", $con);
$sql="SELECT * FROM skudata WHERE packcode = '".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<td>" . $row['Description'] . "</td>";
echo "<td>" . $row['SellingUnits'] . "</td>";
echo "<td>" . $row['EOTTPoints'] . "</td>";
echo "<td>" . $row['Category'] . "</td>";
echo "<td>" . $row['Grouping'] . "</td>";
}
mysql_close($con);
?>
The problem here is that you've used two ideas that don't quite work together. This line: document.getElementById("txtHint").innerHTML=xmlhttp.responseText; is setting the content of the tag with id "txtHint" to what your php script returns. This means that when your php returns, for example:
<td>blah</td><td>blah</td><td>blah</td>
then your page ends up with:
<div id="txtHint">
<td>blah</td>
<td>blah</td>
<td>blah</td>
</div>
Do you see what's happening here? You aren't adding more cells to the existing row, you're creating another table within the cell you already have (and a bad one at that, with no <table> or <tr> tags...).
To get around this, change the element with id "txtHint" to the <tr> tag for the row you are editing, and update the php to return the first cell of that row as well, eg:
HTML:
<table border=1>
<tr>
<td>SKU</td>
<td>Description</td>
<td>SU</td>
<td>Points</td>
<td>Category</td>
<td>Grouping</td>
</tr>
<tr id="txtHint">
<td>
<select name="users" onchange="showUser(this.value)">
<OPTION VALUE=0>
<?=$optionssku?>
</SELECT>
</td>
<td colspan="5">SKU Details will be seen here</td>
</tr>
PHP:
while($row = mysql_fetch_array($result))
{
echo "<td><select name='users' onchange='showUser(this.value)'><OPTION VALUE=0>";
echo $optionssku; //Not sure where this variable comes from, so I'll leave getting it from wherever necessary to you
echo "</SELECT></td>";
echo "<td>" . $row['Description'] . "</td>";
echo "<td>" . $row['SellingUnits'] . "</td>";
echo "<td>" . $row['EOTTPoints'] . "</td>";
echo "<td>" . $row['Category'] . "</td>";
echo "<td>" . $row['Grouping'] . "</td>";
}
(code not tested, but it'll be something like this).
There are certainly other methods to get around this problem, almost certainly better ones, but this is the first idea that came to me.

Categories