PHP multiple select - option data sending with ajax [duplicate] - php

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>

Related

fetch data using ajax in php

I have two tables in my database first one id and the other one text.
I can fetch the data from db like this way
this is index.php file
<?php include "config.php"?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<ul>
<?php
$result = $db->query("select * from veri ORDER BY id DESC ");
while ($row = $result->fetch_object()) {
echo '<li id="'.$row->id.'">'.$row->text.'</li>';
}
?>
</ul>
</body>
</html>
I am required to check the database every five seconds if a new item inserted or not.
I am using this code below.But It doesnt work.I have no idea what is wrong ?can you please help and thank in advance
ajax.js file
$(function () {
$ajaxLoad = function () {
var lastid = $("ul li:first").attr("id");
$.ajax({
type: "post",
url: "ajax.php",
data: {"lastid": lastid},
dataType: "json",
success: function (result) {
if (result.error) {
$("#result").html(result);
}
else{
$("ul").prepend(result.data);
}
}
});
}
setInterval("ajaxLoad()",5000);
});
this ajax.php file
<?php
require "config.php";
if ($_POST) {
$lastid = $_POST["lastid"];
if (!$lastid) {
$array["error"] = "something is wrong";
} else {
$query = $db->query("select * from veri where id>$lastid ORDER by id DESC ");
if (mysqli_affected_rows()) {
while ($row = $query->fetch_object()) {
$array["data"]='<li id="'.$row->id.'">'.$row->text.'</li>';
}
} else {
$array["error"] = " there is no new record";
}
}
echo json_encode($array);
}
?>
Your setInverval() accepts a callback function as first parameter. You passed a string. It should be:
setInterval(ajaxLoad, 5000);
And also, remove the $ from the $ajaxLoad definition. It's JavaScript, not PHP. In case that you would want to prepend the $ to your variable, you must also use that variable along with the $ like so:
$variable = 5;
console.log($variable); // prints 5 to the console
However, it is absolutely bad practice since you will get confused as to whether you are using PHP or JS.
Here also you did a mistake. As per the current code you may get only last record inserted instead of all new inserted records because you are not concatenating the records. This is one way to solve it:
<?php
require "config.php";
if ($_POST)
{
$lastid = $_POST["lastid"];
if (!$lastid)
{
$array["error"] = "something is wrong";
}
else
{
$query = $db->query("select * from veri where id>$lastid ORDER by id DESC ");
if (mysqli_affected_rows())
{
$new_rows = "";
while ($row = $query->fetch_object())
{
$new_rows .= '<li id="'.$row->id.'">'.$row->text.'</li>';
}
$array["data"]=$new_rows;
}
else
{
$array["error"] = " there is no new record";
}
}
echo json_encode($array);
}
?>

How can I get a select option value in a form before submit? [duplicate]

I have database consists of countries and cities.
First Case - Successfully done:
Country list gets populated in drop box on page load
City list gets populated in drop box on page load - populated city list
is based on the default country.
Second Case - Couldn't make it:
User changes country
City list will be changed according to selected country
I know i have to use jQuery/Ajax. I tried but i couldn't solve my problem due to my lack of programming experience. My list is fetched from database not XML. I just need a quick solution, i need to keep it simple and stupid.
I'm using regular PHP coding style, not Object-Oriented.
How can i do it? Any related resources will be appreciated.
$("#country").change(function(){
$('#city').find('option').remove().end(); //clear the city ddl
var country = $(this).find("option:selected").text();
alert(country);
//do the ajax call
$.ajax({
url:'getCity.php'
type:'GET',
data:{city:country},
dataType:'json',
cache:false,
success:function(data){
data=JSON.parse(data); //no need if dataType is set to json
var ddl = document.getElementById('city');
for(var c=0;c<obj.length;c++)
{
var option = document.createElement('option');
option.value = obj[c];
option.text = obj[c];
ddl.appendChild(option);
}
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
});
in your getCity.php
$country = $_GET['city'];
//do the db query here
$query = "your query";
$result = mysql_query($query);
$temp = array();
while ($row = mysql_fetch_assoc($result)) {
if(empty($temp))
{
$temp=array($row['city']);
}
else
{
array_push($temp,$row['city']);
}
}
echo (json_encode($temp));
You can do that by making ajax call on change of select box value by using .change() method of jquery. api.jquery.com/change/
write data instead of obj. It works perfectly fine
index.php
<?php
require_once './db.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>StackOverFlow</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<?php
// In this part of the code i'm building the select box options
$sql = "SELECT thana FROM locations group by thana";
$stmt = $conn->prepare($sql);
$stmt->execute();
?>
<select name="Thana" class="thana-select-box">
<option></option>
<?php
while ($row = $stmt->fetch()){ ?>
<option value="<?=$row['thana']?>"><?=$row['thana']?></option>
<?php } ?>
</select>
<select name="Area" class="area-select-box">
</select>
</body>
</html>
db.php
<?php
$username = 'your username';
$password = 'your password';
$host = 'localhost';
$dbname = 'test';
$conn = new PDO("mysql:host=$host;dbname=$dbname",$username, $password
,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
));
get_options.php
<?php
require_once 'db.php';
$thana = $_REQUEST['thana'];
$sql = "SELECT area FROM locations where thana='$thana'";
$stmt = $conn->prepare($sql);
$stmt->execute();
$options = [];
while ($row = $stmt->fetch()){
$options[] = $row['area'];
}
echo json_encode($options);
app.js:
$(document).ready( function(){
$(document).on('change', '.thana-select-box', function(e){
let fd = new FormData();
let thana = $(this).val();
fd.append('thana', thana);
// In this part of the code according to the selected thana, we are going to fetch
// the rows from the second table Area, the php will return a json structure that contains the rows
// or more with the Area that belong to thana.
$.ajax({
url: "get_options.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
complete: function (results) {
try {
let str = JSON.parse(results.responseText);
updateDOM(str);
console.log(str)
} catch (e) {
console.error(e.message);
}
},
});
});
updateDOM = (options) => {
let areaSelectBox = $('.area-select-box');
let options_dom = '';
options.map((value)=>{
options_dom += `<option value="${value}">${value}</option>`;
});
areaSelectBox.html ('');
areaSelectBox.append(options_dom);
};
});

How to make a Cascading Drop Down List in PHP using jQuery

I have database consists of countries and cities.
First Case - Successfully done:
Country list gets populated in drop box on page load
City list gets populated in drop box on page load - populated city list
is based on the default country.
Second Case - Couldn't make it:
User changes country
City list will be changed according to selected country
I know i have to use jQuery/Ajax. I tried but i couldn't solve my problem due to my lack of programming experience. My list is fetched from database not XML. I just need a quick solution, i need to keep it simple and stupid.
I'm using regular PHP coding style, not Object-Oriented.
How can i do it? Any related resources will be appreciated.
$("#country").change(function(){
$('#city').find('option').remove().end(); //clear the city ddl
var country = $(this).find("option:selected").text();
alert(country);
//do the ajax call
$.ajax({
url:'getCity.php'
type:'GET',
data:{city:country},
dataType:'json',
cache:false,
success:function(data){
data=JSON.parse(data); //no need if dataType is set to json
var ddl = document.getElementById('city');
for(var c=0;c<obj.length;c++)
{
var option = document.createElement('option');
option.value = obj[c];
option.text = obj[c];
ddl.appendChild(option);
}
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
});
in your getCity.php
$country = $_GET['city'];
//do the db query here
$query = "your query";
$result = mysql_query($query);
$temp = array();
while ($row = mysql_fetch_assoc($result)) {
if(empty($temp))
{
$temp=array($row['city']);
}
else
{
array_push($temp,$row['city']);
}
}
echo (json_encode($temp));
You can do that by making ajax call on change of select box value by using .change() method of jquery. api.jquery.com/change/
write data instead of obj. It works perfectly fine
index.php
<?php
require_once './db.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>StackOverFlow</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<?php
// In this part of the code i'm building the select box options
$sql = "SELECT thana FROM locations group by thana";
$stmt = $conn->prepare($sql);
$stmt->execute();
?>
<select name="Thana" class="thana-select-box">
<option></option>
<?php
while ($row = $stmt->fetch()){ ?>
<option value="<?=$row['thana']?>"><?=$row['thana']?></option>
<?php } ?>
</select>
<select name="Area" class="area-select-box">
</select>
</body>
</html>
db.php
<?php
$username = 'your username';
$password = 'your password';
$host = 'localhost';
$dbname = 'test';
$conn = new PDO("mysql:host=$host;dbname=$dbname",$username, $password
,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
));
get_options.php
<?php
require_once 'db.php';
$thana = $_REQUEST['thana'];
$sql = "SELECT area FROM locations where thana='$thana'";
$stmt = $conn->prepare($sql);
$stmt->execute();
$options = [];
while ($row = $stmt->fetch()){
$options[] = $row['area'];
}
echo json_encode($options);
app.js:
$(document).ready( function(){
$(document).on('change', '.thana-select-box', function(e){
let fd = new FormData();
let thana = $(this).val();
fd.append('thana', thana);
// In this part of the code according to the selected thana, we are going to fetch
// the rows from the second table Area, the php will return a json structure that contains the rows
// or more with the Area that belong to thana.
$.ajax({
url: "get_options.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
complete: function (results) {
try {
let str = JSON.parse(results.responseText);
updateDOM(str);
console.log(str)
} catch (e) {
console.error(e.message);
}
},
});
});
updateDOM = (options) => {
let areaSelectBox = $('.area-select-box');
let options_dom = '';
options.map((value)=>{
options_dom += `<option value="${value}">${value}</option>`;
});
areaSelectBox.html ('');
areaSelectBox.append(options_dom);
};
});

Refresh comments section [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have put together a JQuery script that when entering a comment, it goes to a database and pulls the result back and displays it on the page. This works well, however I need a seperate page with just the comments on, which auto refreshes the results every 5 seconds (instead of clicking refresh on the browser). What I would also like is for the comments to FadeIn. I have tried to do this with resources I have found online, but most of them seem to keep replicating my content as well as refreshing.
Can you help?
Comments.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="comments.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Live Comments</title>
</head>
<body>
<div id="leaveComment">
<h2>Leave a Comment</h2>
<div class="row">
<label>Your Name:</label>
<input type="text">
</div>
<div class="row">
<label>Comment:</label>
<textarea cols="10" rows="5"></textarea>
</div>
<button id="add">Add</button>
</div>
<div id="comments">
<h2>Live Comments</h2>
</div>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$(function() {
//retrieve comments to display on page
$.getJSON("comments.php?jsoncallback=?", function(data) {
//loop through all items in the JSON array
for (var x = 0; x < data.length; x++) {
//create a container for each comment
var div = $("<div>").addClass("row").appendTo("#comments");
//add author name and comment to container
$("<label>").text(data[x].name).appendTo(div);
$("<div>").addClass("comment").text(data[x].comment).appendTo(div);
}
});
//add click handler for button
$("#add").click(function() {
//define ajax config object
var ajaxOpts = {
type: "post",
url: "addComment.php",
data: "&author=" + $("#leaveComment").find("input").val() + "&comment=" + $("#leaveComment").find("textarea").val(),
success: function(data) {
//create a container for the new comment
var div = $("<div>").addClass("row").appendTo("#comments");
//add author name and comment to container
$("<label>").text($("#leaveComment").find("input").val()).appendTo(div);
$("<div>").addClass("comment").text($("#leaveComment").find("textarea").val()).appendTo(div).hide().fadeIn("slow");
//empty inputs
$("#leaveComment").find("input").val("");
$("#leaveComment").find("textarea").val("");
}
};
$.ajax(ajaxOpts);
});
});
</script>
</body>
</html>
Moderator.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="comments.css">
</head>
<body>
<div id="comments">
<h2>Live Comments</h2>
</div>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$(function() {
//retrieve comments to display on page
$.getJSON("comments.php?jsoncallback=?", function(data) {
//loop through all items in the JSON array
for (var x = 0; x < data.length; x++) {
//create a container for each comment
var div = $("<div>").addClass("row").appendTo("#comments");
//add author name and comment to container
$("<label>").text(data[x].name).appendTo(div);
$("<div>").addClass("comment").text(data[x].comment).appendTo(div);
}
});
//add click handler for button
$("#add").click(function() {
//define ajax config object
var ajaxOpts = {
type: "post",
url: "addComment.php",
data: "&author=" + $("#leaveComment").find("input").val() + "&comment=" + $("#leaveComment").find("textarea").val(),
success: function(data) {
//create a container for the new comment
var div = $("<div>").addClass("row").appendTo("#comments");
//add author name and comment to container
$("<label>").text($("#leaveComment").find("input").val()).appendTo(div);
$("<div>").addClass("comment").text($("#leaveComment").find("textarea").val()).appendTo(div).hide().fadeIn("slow");
//empty inputs
$("#leaveComment").find("input").val("");
$("#leaveComment").find("textarea").val("");
}
};
$.ajax(ajaxOpts);
});
});
</script>
</body>
</html>
Comments.php
<?php
//db connection detils
$host = "localhost";
$user = "CommentsDB";
$password = "password";
$database = "comments";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//query the database
$query = mysql_query("SELECT * FROM comments");
//loop through and return results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
$comments[$x] = array("name" => $row["name"], "comment" => $row["comment"]);
}
//echo JSON to page
$response = $_GET["jsoncallback"] . "(" . json_encode($comments) . ")";
echo $response;
?>
addComments.php
<?php
//db connection detils
$host = "localhost";
$user = "CommentsDB";
$password = "password";
$database = "comments";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//get POST data
$name = mysql_real_escape_string($_POST["author"]);
$comment = mysql_real_escape_string($_POST["comment"]);
//add new comment to database
mysql_query("INSERT INTO comments VALUES(' $name ',' $comment ')");
?>
QUOTE: auto refreshes the results every 5 seconds
use this code.
function checkForComments() {}
$(document).ready(function () {
//Wait 5 seconds then call checkForComments();
setInterval("checkForComments()", 5000);
});
5000 here is time in milliseconds equivalent to 5 seconds.
QUOTE: but most of them seem to keep replicating my content as well as refreshing.
It isn't clear from your question what exactly does comments.php output. If it outputs all the comments in the database best option would be to keep an array of the ids of the comments that have been posted to page. Just write a function in JavaScript that checks if a particular id exists in that array and append it if it doesn't.
QUOTE: What I would also like is for the comments to FadeIn
follow this question
Making my ajax updated div fade in
UPDATED
JavaScript to load comments
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
//stores the comment IDs
var comments=new Array();
var count=1 ;
function checkForComments() {
$.getJSON("comments.php", addComments);
}
function addComments(data) {
//loop through all items in the JSON array
for (var x = 0; x < data.length; x++) {
alert(data[x].id);
if(jQuery.inArray(data[x].id, comments)==-1){
comments[count] = data[x].id;
//create a container for each comment
var div = $("<div>").addClass("row").appendTo("#comments");
//add author name and comment to container
$("<label>").text(data[x].name).appendTo(div);
$("<div>").addClass("comment").text(data[x].comment).appendTo(div);
count++;
}
}
}
$(document).ready(function () {
checkForComments();
setInterval("checkForComments()", 5000);
});
</script>
my comments.php
<?php
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//query the database
$query = mysql_query("SELECT * FROM comments");
//loop through and return results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
//I have added ID here,
$comments[$x] = array("id" => $row["id"], "name" => $row["name"], "comment"
=> $row["comment"]);
}
echo json_encode($comments);
?>
SQL for comments table
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
`comment` text NOT NULL,
PRIMARY KEY (`id`)
)
You have two choices: After adding append()ing the new content, remove the old content.
Or, set a "placeholder" element, and use .html() on it - that way you replace the old content, you don't add more.

using JQuery with mySQL confusion

HI,
I have code like this. what I am doing is populating the first select with the MySQL data and based on the selection the first , using jQuery, I am populating the second one. Now, my question is, can I use the same combos_get.php to populate the another select based on user selection from the second select?
Is yes, then please look at the comment 'stuck at this point' where I am confused on how to get the data on the the third select.
<html>
<head>
<link href="style23.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title></title>
</head>
<body>
<div align="left" style="position:absolute;top:10px;">
<select name="select1" id="select1" size="10px;">
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "bob") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
$result = mysql_query("select * from results where ID NOT LIKE 'Ex%' ") or die(mysql_error());
// store the record of the "example" table into $row
while($row = mysql_fetch_array( $result )) {
// Print out the contents of the entry
?>
<option value="<?php echo $row['ID']; ?>"><?php echo $row['ID'] ?></option>
<?php
}
?>
</select><br>
<script type="text/javascript">
$(document).ready(function() {
$('#select1').change(getDropdownOptions);
// $('#select2').change(getDropdownOptions); // stuck at this point
});
function getDropdownOptions() {
var val = $(this).val();
//alert(val);
// fire a POST request to combos_get.php
$.post('combos_get.php', { value : val }, populateDropdown, 'html');
//alert('s');
}
function populateDropdown(data) {
if (data != 'error') {
$('#select2').html(data);
}
}
</script>
</div>
<div align="left" style="position:relative;left:250px;">
<select name="select2" size="10px;" id="select2">
<option value="--">--</option>
</select>
</div>
<div style="position:relative;left:450px;top:10px">
<select name="select3" size="10px;" id="select3">
<option value="--">--</option>
</select>
</div>
</body>
</html>
**combos_get.php**
<?php
if (!empty($_POST['value'])) {
$val = $_POST['value'];
mysql_connect("localhost", "root", "bob") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
$result = mysql_query("select ID2 from results where ID = \"$val\" ") or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
$html .= '<option value="1">'.$row['ID2'].'</option>';
}
die($html);
}
die('error');
?>
You will more than likely want another handler for this case. It's up to you whether or not the same PHP file can handle the query, however:
$(document).ready(function() {
$('#select1').change(getDropdownOptions);
$('#select2').change(getSecondDropdownOptions);
});
function getSecondDropdownOptions() {
var val = $(this).val();
$.post('combos_get.php', { value : val }, populateSecondDropdown, 'html');
}
function populateSecondDropdown(data) {
if (data != 'error') {
$('#YOURNEXTSELECT').html(data);
}
}
Common practice is to reuse as much code as possible. I don't have time to refactor since I just got to work but someone is more than welcome to clean this up for him.
In order to do that you need to make populateDropdown use a dynamic target.
something like:
function getDropdownOptions(event) {
var e = $(this);
var val = e.val();
// fire a POST request to combos_get.php
$.post('combos_get.php',{ value : val }, function(data){
populateDropdowns(data, e);
}, 'html');
}
function populateDropdown(data, e) {
// e is our originating select
/* HERE You need to come up with a way to determin the target to populate based on the element that triggered it. for example assuming you only have 3 selects:*/
switch(e.attr(id)){
case 'select2':
var targetSelector = '#select3';
break;
case 'select1':
var targetSelector = '#select2';
break;
default:
var targetSelector = null;
break;
}
if (data != 'error' && targetSelector) {
$(targetSelector).html(data);
}
}

Categories