I am trying to create a dependent dropdown using php and ajax. What I am expecting is when the 'Make' of car is selected the relevant car models should automatically load on the 'Model' dropdown. I have manged to do the preloading of 'Make' of cars. But the 'Model' dropdown remains empty. I have used a single tale and in sql statement used (select model where make= selected make). here is my code
php
<form method="GET">
<div class="form-group">
<select class="form-control" name="make" id="make">
<option value="" disabled selected>--Select Make--</option>
<?php
$stmt=$pdo->query("SELECT DISTINCT make FROM cars WHERE cartype='general' ");
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?= $row['make']; ?>"> <?= $row['make']; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<select class="form-control" name="model" id="model">
<option value="" disabled selected>--Select Model--</option>
</select>
</div>
.......
....
.....
script
<script type="text/javascript">
$(document).ready( function () {
// alert("Hello");
$(#make).change(function(){
var make = $(this).val();
$.ajax({
url:"filter_action.php",
method:"POST",
data:{Make:make},
success: function(data){
$("#model").html(data);
});
});
});
</script>
filter_action.php
<?php
include('db_config2.php');
$output='';
$stmt=$pdo->query("SELECT DISTINCT model FROM cars WHERE cartype='general' AND make= '".$_POST['Make']."'");
$output .='<option value="" disabled selected>--Select Model--</option>';
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
$output .='<option value="'.$row["model"].'">'.$row["model"].'</option>' ;
}
echo $output;
?>
There appeared to be a couple of mistakes in the Javascript that would have been obvious in the developer console and your PHP had left the mySQL server vulnerable to sql injection attacks.
<script>
$(document).ready( function () {
// The string should be within quotes here
$('#make').change(function(e){
var make = $(this).val();
$.ajax({
url:"filter_action.php",
method:"POST",
data:{'Make':make},
success: function(data){
$("#model").html(data);
};//this needed to be closed
});
});
});
</script>
The direct use of user supplied data within the sql opened your db to sql injection attacks. To mitigate this you need to adopt "Prepared Statements" - as you are using PDO anyway this should be a matter of course.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['Make'] ) ){
# The placeholders and associated values to be used when executing the sql cmd
$args=array(
':type' => 'general', # this could also be dynamic!
':make' => $_POST['Make']
);
# Prepare the sql with suitable placeholders
$sql='select distinct `model` from `cars` where `cartype`=:type and `make`=:make';
$stmt=$pdo->prepare( $sql );
# commit the query
$stmt->execute( $args );
# Fetch the results and populate output variable
$data=array('<option disabled selected hidden>--Select Model--');
while( $rs=$stmt->fetch(PDO::FETCH_OBJ) )$data[]=sprintf('<option value="%1$s">%1$s', $rs->model );
# send it to ajax callback
exit( implode( PHP_EOL,$data ) );
}
?>
I have try this using php pdo.
first i have create a 3 files.
db.php
htmlDropdown.php
modelAjax.php
here, db.php file can contain my database connection code. and htmlDropdown.php file contain my dropdown for car and models. and modelAjax.php file contain ajax to fetch all models.
db.php
<?php
$host_name = 'localhost';
$user_name = 'root';
$password = '';
$db_name = 'stackoverflow';
$conn = new PDO("mysql:host=$host_name; dbname=$db_name;", $user_name, $password);
?>
htmlDropdown.php
<?php include "db.php"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cars</title>
<!-- jQuery cdn link -->
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<!-- Ajax cdn link -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxy/1.6.1/scripts/jquery.ajaxy.min.js" integrity="sha512-bztGAvCE/3+a1Oh0gUro7BHukf6v7zpzrAb3ReWAVrt+bVNNphcl2tDTKCBr5zk7iEDmQ2Bv401fX3jeVXGIcA==" crossorigin="anonymous"></script>
</head>
<body>
<?php
$car_sql = 'SELECT car_name FROM cars'; //select all cars query
$cars_statement = $conn->prepare($car_sql);
$cars_statement->execute();
?>
<select name="car" id="car">
<option value="">Cars</option>
<?php
while ($cars = $cars_statement->fetch()) { // fetch all cars data
?>
<option value="<?php echo $cars['car_name']; ?>"><?php echo $cars['car_name']; ?></option>
<?php
}
?>
</select><br><br>
<select name="model" id="model">
<option value="">Model</option>
</select>
</body>
</html>
<script>
$(document).ready(function () {
$('#car').on("change", function () {
let car = $(this).val(); // car value
$.post("http://local.stackoverflowanswer1/cars/modelAjax.php", { car_name : car }, function (data, status) { // ajax post send car name in modelAjax.php file
let datas = JSON.parse(data); // convert string to json object
let options = '';
options = '<option>Model</option>';
$.each(datas.model, function (key, value) {
options += "<option>"+value.modal_name+"</option>";
});
$('#model').html(options);
});
});
});
</script>
modelAjax.php
<?php
include "db.php";
if ($_POST['car_name'])
{
$car_id_sql = "SELECT id FROM cars WHERE car_name LIKE ?"; // get id from given car name
$id_statement = $conn->prepare($car_id_sql);
$id_statement->execute([$_POST['car_name']]);
$id = $id_statement->fetch();
$model_sql = "SELECT modal_name FROM models WHERE car_id = ?"; // get model name from given id
$model_statement = $conn->prepare($model_sql);
$model_statement->execute([$id['id']]);
$models = $model_statement->fetchAll();
echo json_encode(["model" => $models]); // i have a conver array to json object
}
?>
Related
I have an input text that is correctly populate with Twitter Typeahead. In this case i would like to select a value from select box and populate the input text with values that are related with selected dropdownlist value. I found similar questions about my doubt but unfortunatly i didnt get the correct way to solve this:
Dynamically populating Twitter Bootstrap Typeahead
Twitter bootstrap Typeahead to populate hrefs
jQuery Autocomplete / Twitter Typeahead Populate Multiple Fields
Below is the code that display a select box that is populate with php code and an input text that is populated with Twitter TypeAhead script:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
</head>
<body>
<div class="container">
<br>
<h1>DYNAMIC TWITTER TYPEAHEAD</h1>
<br>
<div class="row">
<?php
// Include the database config file
include_once 'dbConfig.php';
// Fetch all the category data
$query = "SELECT * FROM categories ORDER BY category ASC";
$result = $db->query($query);
?>
<!-- category dropdown -->
<div class="col-md-4">
<select id="categoryFK" name="categoryFK" class="form-control">
<option value="">Select category</option>
<?php
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<option value="'.$row['categoryID'].'">'.$row['category'].'</option>';
}
}else{
echo '<option value="">Category not available</option>';
}
?>
</select>
</div>
<div class="col-md-4">
<input type="text" name="products" id="products" class="form-control input-lg" autocomplete="off" placeholder="" />
</div>
</div>
</div>
</body>
</html>
Below is the script that call php script via Ajax:
<script>
$(document).ready(function(){
$('#categoryFK').on('change', function(){
var queryID = $(this).val();
if(queryID){
$('#products').typeahead({
source: function(query, result)
{
$.ajax({
url:"fetch.php",
method:"POST",
data: 'query='+queryID,
dataType:"json",
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
}
});
});
</script>
And below is the php script (fetch.php) that populate values according to categoryID:
<?php
//fetch.php
include 'dbConfig.php';
if(!empty($_POST["query"])){
$request = mysqli_real_escape_string($db, $_POST["query"]);
$query = "
SELECT * FROM products WHERE productName LIKE '%".$request."%' AND categoryFK = ".$_POST["query"]."
";
$result = $db->query($query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row["productName"];
}
echo json_encode($data);
}
}
?>
As i showed the code above, when i type something into input text after i selected any option into select box, the input text with Twitter TypeAhead just populate one register.
In this case, how can i improve php code above to populate input text with values related with select box value correctly? Thanks.
I managed to solve the problem. Below are the scripts that i modified to adapt on my project:
AJAX
<script type="text/javascript">
var products;
$ ( function ()
{
$('#categoryFK').on('change', function(){
var queryID = $(this).val();
$.ajax({
url:"fetch.php",
method:"POST",
data: {
category: queryID
},
dataType:"json",
success:function(data)
{
$("#products").val ('');
products = data;
}
});
});
$('#products').typeahead({
source: function ( query, result )
{
result ( $.map(products, function (item)
{
return item;
}
));
}
});
});
</script>
And PHP script (fetch.php)
<?php
include 'dbConfig.php';
if ( isset ( $_POST [ 'category' ] ) ) {
$request = $db->real_escape_string($_POST["category"]);
$query = "
SELECT * FROM products WHERE categoryFK = ".$request."
";
$result = $db->query($query);
$data = array ();
if ( $result->num_rows > 0 )
{
while($row = $result->fetch_assoc ())
{
$data[]=$row["productName"];
}
echo json_encode($data);
}
}
?>
Now, with these modifications, i can select an option into "category" select box and after, type into input text where all valus related with selected option will be load :)
I'm trying to create a program that when you select a state from the drop down menu, it will display the list of cities for that state in another drop down menu that you can select from. After you choose your city and state, you type in an address, hit submit, and it will display the full address on a new php file.
My issue at the moment is I can get the states displayed, but when the state is selected, it is not giving me the list of options for that city in the second drop down menu. Any help is appreciated, thanks!
You can view the behavior at this link
select.php
<head>
<link rel="stylesheet" type="text/css" href="select_style.css">
<script type="text/javascript" src="js/jquery.js"></script>
<!DOCTYPE html>
<form action = "display.php">
<script type="text/javascript">
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'fetch.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
});
}
</script>
</head>
<body>
<p id="heading">Address Generator</p>
<center>
<div id="select_box">
<select onchange="fetch_select(this.value);">
<option>Select state</option>
<?php
include ( "accounts.php" ) ;
( $dbh = mysql_connect ( $hostname, $username, $password ) )
or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db( $project );
$select=mysql_query("select state from zipcodes group by state");
while($row=mysql_fetch_array($select))
{
echo "<option>".$row['state']."</option>";
}
?>
</select>
<select id="new_select">
</select>
<div id='2'> </div>
<br><br>
<input type = text name="address">Address
<br><br>
<input type = submit>
</form>
fetch.php
<?php
include(accounts.php);
if(isset($_POST['get_option']))
{
( $dbh = mysql_connect ( $hostname, $username, $password ) )
or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db( $project );
$state = $_POST['get_option'];
$find=mysql_query("select city from zipcodes where state='$state'");
while($row=mysql_fetch_array($find))
{
echo "<option>".$row['city']."</option>";
}
exit;
}
?>
1)First of all your state option's value attribute is missing
echo "<option value='".$row["state"]."'>".$row["state"]."</option>";
2)Include(accounts.php); accounts.php should be enclosed by double quotes
3) And city option's value attribute is missing
echo "<option value='".$row["city"]."'>".$row["city"]."</option>";
4) Instead of echoing each time concatenate and echo finally like this
$options="";
while($row=mysql_fetch_array($find))
{
$options.= "<option value='".$row["city"]."' >".$row["city"]."</option>";
}
echo $options;
Warning!!!
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
I've modified your code a little. Tried to do it the elegant way. You had wrote too much of superfluous code. You didn't need a <form> element to perform the asked operation. Anyway below is the modified code.
<!DOCTYPE html>
<head>
<title>Address Generator</title>
</head>
<body>
<p id="heading">Address Generator</p>
<center>
<!-- <div id="select_box"> -->
<select name="select_box" id="select_box">
<?php
include ( "accounts.php" ) ;
( $dbh = mysql_connect ( $hostname, $username, $password ) ) or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db( $project );
$select=mysql_query("select state from zipcodes group by state");
while($row=mysql_fetch_array($select))
{
echo "<option>".$row['state']."</option>";
}
?>
</select>
<select id="new_select">
</select>
<div id='2'> </div>
<br><br>
<input type = text name="address">Address
<br><br>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#select_box').on('change', function() {
var state = $(this).val();
$.ajax({
url: 'fetch.php',
type: 'POST',
data: {state: state},
success: function(response)
{
var response = JSON.parse(response);
$('#new_select').find('option').remove();
var option = '';
$.each(response.cities, function(key, val) {
option = option + "<option value='" + val + "'>" + val + "</option>";
});
$('#new_select').append(option);
}
});
});
});
</script>
</body>
I've added Jquery before the end of </body> tag. This doesn't hinder your current code execution. However you could always preload it but that tactic is for later.
Since you didn't need any <form> element so I've completely removed it. You can always add it according to your convenience.
I'm running a loop on the cities array of the object response that I'm getting from fetch.php.
parsing the JSON data using JSON.parse() function.
You'll need to json_encode your json variable which will store the corresponding citites data.
I hope this helps. Any further queries are welcome too.
On my web page I have two dropdown menus. One for a list of countries and another for a list of city's. The country menu is populated with data from a database. Once one of these countries are selected, the following dropdown is populated with corresponding cities via a php file (getdata.php) which takes the country value selected and queries it with a database and echos the city names into the dropdown. What I am struggling to work out is, when a city is selected, how would I get the text of the city selection and use this text in another php (displayCity.php) to query the database and echo values such as Population into the textbox (without reloading page) back on the web page? Would I need to make the displayCity.php similar to the getData.php? I have already created a new Ajax method for the textbox but I am not sure if I will need this. Advice would be greatly appreciated.
<?php include_once "connection.php"; ?>
<!DOCTYPE html>
<html>
<head>
<title>City displayer</title>
<h1>City displayer</h1>
<link rel="stylesheet" type="text/css" href="homepagestyle.css">
</head>
<body>
<div class = "country">
<label>Select Country: </label>
<select name="country" onchange="getId(this.value);">
<option value = "">Select Country</option>
<?php
$query = "SELECT DISTINCT(Country) from location AS Country FROM location ORDER BY Country ASC;";
$results = mysqli_query($con, $query);
foreach ($results as $country) {
?>
<option value = "<?php echo $country['Country']; ?>"><?php echo $country['Country'] ?></option>
<?php
}
?>
</select>
</div>
</br>
</br>
<div class="city">
<label>Select a City: </label>
<select name="city" id="cityList" onchange="showCity(this.value)">
<option value="">Select a city</option>
</select>
</div>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
function getId(value){
$.ajax({
type: "POST",
url: "getdata.php",
data: "Country="+value,
success: function(data){
$("#cityList").html(data);
}
});
}
</script>
</br>
<div id = "textbox">Choose a country and city to display city name here</div>
<script>
function showCity(value){
$.ajax({
type: "POST",
url: "displayCity.php",
data: "City="+value,
success: function(data){
$("#textbox").html(data);
}
});
}
</script>
</body>
</html>
getdata.php
<?php
include_once "connection.php";
if(!empty($_POST['Country'])){
$country = $_POST['Country'];
$query = "SELECT * FROM location WHERE Country= '$country'";
$results = mysqli_query($con, $query);
foreach ($results as $city) {
?>
<option value = "<?php echo $city['Country']; ?>"><?php echo
$city['City'] ?></option>
<?php
}
}
?>
Use AJAX along with a $_SESSION variable. No need to write it to the database. You just have to make sure you use session_start() everywhere you need it.
New in php and ajax, building a dropdown based on another dropdown through database.Up to now code is sucessfully running, you can check my code having two php pages, dropdown2.php and postbrand.php now just want to know how to use $brand variable value in postbrand.php to use in the sql query in second dropdown in dropdown2.php.
<?php
require 'connect.inc.php';
$query = "SELECT * FROM `brand` ";
$data = mysql_query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Input form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12/jquery.min.js"></script>
</head>
<body>
<form>
<label>Brand:</label>
<select name="brand" id="sb" onchange="myFunction()">
<?php
while($row=mysql_fetch_array($data))
{
?>
<option value="<?php echo $row['b_name'];?>">
<?php
echo $row['b_name'];
?>
</option>
<?php
}
?>
</select>
<br/><br/>
<label>Model:</label>
<?php
$query = "SELECT model.model, model.b_id from model inner join brand on model.b_id= brand.b_id where brand.b_name like 'sony'";
$result = mysql_query($query);
$select= '<select name="select" id="sm">';
while($rs=mysql_fetch_array($result)){ $select.='<option value="'.$rs['b_id'].'">'.$rs['model'].'</option>';
}
$select.='</select>';
echo $select;
?>
</form>
<div id="result"></div>
<script>
function myFunction() {
//alert('working!!');
var brand = $('#sb').val();
$.post('postbrand.php', {postbrand:brand},
function(data){
$('#result').html(data);
});
}
</script>
</body>
</html>
postbrand.php
<?php
$brand = $_POST['postbrand'];
echo $brand;
?>
If I get it correct you want to populate the second dropdown based on the chosen value of the first dropdown.
To steps to achieve this are:
listen to "change" event on the first dropdown (using JQ)
var selected = ""
$('select#sb').on('change', function() {
selected = $(this).val(); // get the chosen value
});
$.post("postbrand.php", selected, function(resp){ //send the selected value to postbrand.php which will return an array of elements from db based on what was selected
$.each(resp,function(key, val){ //traverse the response and
$('select#secondDropdown').append('<option>'+val+'</option>') //populate the 2nd dropdown
})
})
I got a database table called category as shown:
I am trying to do a dynamic drop down box and the index script is shown as:
<?php
try {
$objDb = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `category`
WHERE `master` = 0";
$statement = $objDb->query($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'There was a problem';
}
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Dependable dropdown menu</title>
<meta name="description" content="Dependable dropdown menu" />
<meta name="keywords" content="Dependable dropdown menu" />
<link href="/css/core.css" rel="stylesheet" type="text/css" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="/js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="/js/core.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<form action="" method="post">
<select name="gender" id="gender" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="category" id="category" class="update"
disabled="disabled">
<option value="">----</option>
</select>
<select name="colour" id="colour" class="update"
disabled="disabled">
<option value="">----</option>
</select>
</form>
</div>
</body>
</html>
The update.php is shown as:
<?php
if (!empty($_GET['id']) && !empty($_GET['value'])) {
$id = $_GET['id'];
$value = $_GET['value'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `category`
WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array('<option value="">Select one</option>');
foreach($list as $row) {
$out[] = '<option
value="'.$row['id'].'">'.$row['name'].'</option>';
}
echo json_encode(array('error' => false, 'list' => implode('',
$out)));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
The 2nd drop down box is not showing the values dependent on the 1st drop down box as shown:
Can someone help me please.
Here is an example that will do what you want. Essentially, you can use jQuery / AJAX to accomplish this.
I updated my example code to match your server login / table / field names, so if you copy/paste these two examples into files (call them tester.php and another_php_file.php) then you should have a fully working example to play with.
I modified my example below to create a second drop-down box, populated with the values found. If you follow the logic line by line, you will see it is actually quite simple. I left in several commented lines that, if uncommented (one at a time) will show you what the script is doing at each stage.
FILE 1 -- TESTER.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//alert('Document is ready');
$('#stSelect').change(function() {
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "another_php_file.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#LaDIV').html(whatigot);
$('#theButton').click(function() {
alert('You clicked the button');
});
} //END success fn
}); //END $.ajax
}); //END dropdown change event
}); //END document.ready
</script>
</head>
<body>
<select name="students" id="stSelect">
<option value="">Please Select</option>
<option value="John">John Doe</option>
<option value="Mike">Mike Williams</option>
<option value="Chris">Chris Edwards</option>
</select>
<div id="LaDIV"></div>
</body>
</html>
FILE 2 - another_php_file.php
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
$server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
$login = 'root';
$pword = '';
$dbname = 'test';
mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
mysql_select_db($dbname) or die($connect_error);
//Get value posted in by ajax
$selStudent = $_POST['theOption'];
//die('You sent: ' . $selStudent);
//Run DB query
$query = "SELECT * FROM `category` WHERE `master` = 0";
$result = mysql_query($query) or die('Fn another_php_file.php ERROR: ' . mysql_error());
$num_rows_returned = mysql_num_rows($result);
//die('Query returned ' . $num_rows_returned . ' rows.');
//Prepare response html markup
$r = '
<h1>Found in Database:</h1>
<select>
';
//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
if ($num_rows_returned > 0) {
while ($row = mysql_fetch_assoc($result)) {
$r = $r . '<option value="' .$row['id']. '">' . $row['name'] . '</option>';
}
} else {
$r = '<p>No student by that name on staff</p>';
}
//Add this extra button for fun
$r = $r . '</select><button id="theButton">Click Me</button>';
//The response echoed below will be inserted into the
echo $r;
To answer your question in the comment: "How do you make the 2nd drop down box populate fields that are only relevant to a selected option from the 1st drop down box?"
A. Inside the .change event for the first dropdown, you read the value of the first dropdown box:
$('#dropdown_id').change(function() {
var dd1 = $('#dropdown_id').val();
}
B. In your AJAX code for the above .change() event, you include that variable in the data you are sending to the 2nd .PHP file (in our case, "another_php_file.php")
C. You use that passed-in variable in your mysql query, thereby limiting your results. These results are then passed back to the AJAX function and you can access them in the success: portion of the AJAX function
D. In that success function, you inject code into the DOM with the revised SELECT values.
That is what I am doing in the example posted above:
The user chooses a student name, which fires the jQuery .change() selector
Here is the line where it grabs the option selected by the user:
var sel_stud = $(this).val();
This value is sent to another_php_file.php, via this line of the AJAX code:
data: 'theOption=' + sel_stud,
The receiving file another_php_file.php receives the user's selection here:
$selStudent = $_POST['theOption'];
Var $selStudent (the user's selection posted in via AJAX) is used in the mysql search:
$query = " SELECT * FROM `category` WHERE `master` = 0 AND `name` = '$selStudent' ";
(When changing the example to suit your database, the reference to $selStudent was removed. But this (here, above) is how you would use it).
We now build a new <SELECT> code block, storing the HTML in a variable called $r. When the HTML is fully built, I return the customized code back to the AJAX routine simply by echoing it back:
echo $r;
The received data (the customized <SELECT> code block) is available to us inside the AJAX success: function() {//code block}, and I can inject it into the DOM here:
$('#LaDIV').html(whatigot);
And voila, you now see a second dropdown control customized with values specific to the choice from the first dropdown control.
Works like a non-Microsoft browser.