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.
Related
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
}
?>
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.
I pull data from a MYSQL database to populate a Drop down
<td class="<?php print $Bank_ca_error;?>">Bank Name</td> <td> <select name="Bank" id="Bank" tabindex=24 style="color: <?php print $TextColour;?>"/> <option><?php print $_SESSION['Bank_ca'] ;?></option> <?php //Get Data to populate drop down $BankQuery = "SELECT BankName FROM tblbank ORDER BY BankName"; $BankResult = mysql_query ($BankQuery); While($nt=mysql_fetch_array($BankResult)) { print"<option $nt[BankName]>$nt[BankName]</option>"; } ?> </select> </td>
I would like based on the value selected populate a text input. So Basically Select the Bank from the List and have it autopopulate the Universal Branch Code in the text input.
I saw an example using Jquery, But I am a complete noob when it comes to this and I cannot get it to work properly
I added the following in the Head section
<script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery('#Bank').live('change', function(event) { $.ajax({ url : 'getData.php', type : 'POST', dataType: 'json', data : $('#myform').serialize(), success: function( data ) { for(var id in data) { $(id).val( data[id] ); } } }); }); }); </script>
I then Added this into the getData.php file
<?php include "../../../includes/dbinfo.inc"; //Connect to database mysql_connect($db_host, $db_username, $db_password); #mysql_select_db($db_database) or die("Unable to select database"); $BankName = $_POST['Bank']; // Selected Bank $query = "SELECT * FROM tblbank WHERE BankName ='{$BankName}'"; $result = mysql_query($query); $row = mysql_fetch_array($result) $BranchCode = $row['UniversalCode']; $arr = array( 'input#BranchCode' => $BranchCode ); echo json_encode( $arr ); ?>
and added the Following to around the inputs and dropdown concerned
<form id='myform'> </form>
I tried to use a solution elsewhere on this site but could not get it to work
Your assistance is greatly appreciated
If I understand correctly what you're trying to do, then you do not need ajax, try something like this
<?php
include "../../../includes/dbinfo.inc";
//Connect to database
mysql_connect($db_host, $db_username, $db_password); #mysql_select_db($db_database) or die("Unable to select database");
$res = mysql_query("SELECT UniversalCode, BankName FROM tblbank ORDER BY BankName");
while($row = mysql_fetch_assoc($res)) {
// associative array of banks
$banks[$row['UniversalCode']] = $row['BankName'];
}
?>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('#Bank').change( function() {
// enter in an empty field code of the selected bank
$('#UniversalCode').val( $(this).val() );
});
});
</script>
<td class="<?php print $Bank_ca_error;?>">Bank Name</td>
<td>
<select name="Bank" id="Bank" tabindex=24 style="color: <?php print $TextColour;?>"/>
<? foreach($banks as $code=>$name) { ?>
<option value="<?=$code?>"><?=$name?></option>
<? } ?>
</select>
<input value="" id="UniversalCode">
</td>
I have one big file (for right now) that is supposed to:
take a variable from a select widget in a form (jQuery)
submit the form asynchronously (jQuery)
return records from a database using the variable selected from the form (php)
The problem is, the variable never seems to reach the php code.
Can anyone tell me what I'm doing wrong, please?
My code:
(all on one page)
<script type="text/javascript">
$(function() {
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$.post("index.php", { zip: str}, function(data){
$('result').text(str); }, "json" );
});//end select
});//end function
</script>
<?php include_once ('../cons.php'); ?>
<?php
if (isset($_POST['zip'])){
$value = $_POST['zip'];
}else{
$value = "nada";
}
echo $value;
//I only get "nada"
?>
</head>
<body>
<div id="body">
<form id="findzip"><!-- jQuery will handle the form -->
<select name="zip">
<option value="">Find your zip code</option>
<?php //use php to pull the zip codes from the database
$mysqli_zip = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit();
}
$q_zip = "select distinct(zip) from mc m group by zip";
$r_zip = $mysqli_zip->query($q_zip);
if ((!$r_zip) || ($r_zip == NULL)) {
echo "no results ";
}
while($row_zip = $r_zip->fetch_array(MYSQLI_BOTH)) {
echo "<option value='". addslashes($row_zip['zip']) . "'>" . addslashes($row_zip['zip']) . "</option>;\n";
}//end while
?>
</select>
</form>
<!-- here's where the results go -->
<result></result>
<br/>
</div>
</body>
</html>
Your script as written is echoing out a value like "12345". But your $.post is expecting it to be type json. When I removed the json type it worked perfectly for me.
Try putting an ID on it, like so:
<select name="zip" id="zip">
Then getting the value from it like so:
$("#zip").val();
I have MySQL tables looking like this:
regions table
id | region
-------------------
1 | Region1
2 | Region2
...
and schools table
region_id | school
-------------------
1 | schno1
1 | schno5
1 | schno6
2 | scho120
My page works like this: At first, page populates #regions select menu from db table named "regions". when user selects #region, the JS sends selected region's value to search.php. Server-side PHP script searches db table named "schools" for #region (previously selected menu) value, finds all matches and echoes them.
Now the question is, how can I hide #class and #school select menus, and show only error message "there is no school found in this region" if no matches are found? How to check if there's no result from search.php? I'm a beginner to JS.
My JavaScript looks like this: http://pastie.org/2444922 and the piece of code from form: http://pastie.org/2444929 and finally search.php: http://pastie.org/2444933
Update
I changed my JS but no success.
$(document).ready(function(){
$("#school").hide();
$("#class").hide();
searchSchool = function(regionSelect){
var selectedRegion = $("select[name*='"+regionSelect.name+"'] option:selected").val();
if (selectedRegion!='0'){
$.ajax({
type: "POST",
url : "core/code/includes/search.php",
data: "®ion_id="+selectedRegion,
success: function(result, status, xResponse){
if (result!=null){
$("#school").show();
$("#class").show();
$("#school").html(result);
}else{
$("#error").html("There is no school found in this region");
$("#school").html('');
$("#school").hide();
}
},
error: function(e){
alert(e);
}
});
}else{
$("#error").html('Please select a region first');
$("#school").html('');
$("#school").hide();
$("#class").hide();
}
}
});
You could try this
index.php :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Ajax With Jquery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
searchSchool = function(regionSelect){
var selectedRegion = $("select[name*='"+regionSelect.name+"'] option:selected").val();
if (selectedRegion!='0'){
$.ajax({
type: "POST",
url : "search.php",
data: "®ion_id="+selectedRegion,
success: function(result, status, xResponse){
alert(result);
if (result!=''){
$("#school").show();
$("#school").html(result);
}else{
$("#error").html("There is no school found in this region");
$("#school").html('');
$("#school").hide();
}
},
error: function(e){
alert(e);
}
});
}else{
$("#error").html('Please select a region first');
$("#school").html('');
$("#school").hide();
}
}
</script>
</head>
<body>
<?php
$username="root";
$password="";
$database="test";
mysql_connect('localhost',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM regions";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
echo "<b><center>Database Output</center></b><br><br>";
?>
<select name="region" id="region" onchange="searchSchool(this)">
<option value="0">Please select a Region</option>
<?php
while($data = mysql_fetch_array( $result ))
{
?>
<option value="<?php echo $data['id']?>"><?php echo $data['name']?></option>
<?php
}
?>
</select>
<select name="school" id="school"></select>
<span id="error"></span>
</body>
</html>
Search.php:
<?php
$username="root";
$password="";
$database="test";
mysql_connect('localhost',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
if(isset($_POST['region_id'])) {
$query = "SELECT * FROM schools WHERE region_id='".$_POST['region_id']."'";
$result=mysql_query($query);
$num = mysql_numrows($result);
if ($num>0){
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
}
else{
return null;
}
}
mysql_close();
?>
Well i cannot exactly read through your full code but i can give you a mock up of what you might wanna do.
have both the dependant drop downs wrapped in a div.
<div id="dep1"></div>
<div id="dep2"></div>
Now in server side after making the validations if u find elements create a drop down and send it here or just send an error message.
<?
if($num>0) {
?>
<select>
<?
foreach($element as $ele) {
<option><?=$ele?></option>
}
?>
</select>
<?
} else {
?>
<div class="error">No regions found</div>
<? } ?>
Your js would look something like
$("#dep1").html(loadbar).load("mypage.php","region="+regionid);
I think the issue resides in your jQuery code on lines 27-30. There is no element with ID = cl_dropdown and the comma delimited makes it look for cl_dropdown inside of sch_dropdown.
My guess is that the second select used to have the id cl_dropdown at one point. If so, the HTML for it should look like this:
<select id="cl_dropdown" name="class">
You should also have an element for the message. According to the jQuery, you are supposed to have an #no_sch element but I don't see it.
<div id="no_sch"></div>
Then replace lines 27-30 with the following:
if (!results) {
$("#sch_dropdown").hide();
$("#cl_dropdown").hide();
$('#no_sch').show();
$('#no_sch').text('no matches found');
};