Dependent Drop down list Jquery, AJAX, PHP, MYSQL - php

I am trying to create a dependent drop down list but it doesnt seem to be populating after I make my first selection. Each selection will get data from a MySQL database. In order for the second drop down to have any options (other then a default "select option" value) the user would have to first make a selection on the first drop down After a lot of googling I am having a hard time finding a simple solution to this.
Here is what I have so far,
Drop down lists (I use PHP and MySQL here to generate and output the drop down lists in a getter.php and require_once into an index.php and echo out the drop down)
$accountOptions = "";
$facilityOptions = "";
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
///ACCOUNTS/////
$accountQuery = "SELECT account_id, account_name FROM account";
$accountData = mysqli_query($dbc, $accountQuery);
//loop through data and display all accounts
while ($aRow = mysqli_fetch_array($accountData)) {
$accountOptions .="<option value=\"".$aRow['account_id']."\">" . $aRow['account_name'] . "</option>";
}
$accountDropDown=" <label>Accounts: </label><br>
<select name='account' id='account' onChange='getFacility(this.value)'>
<option selected='selected' disabled='disabled' value=''>Select account</option>
" . $accountOptions . "
</select>";
////FACILITIES/////
$facilityDropDown=" <label>Facility: </label><br>
<select name='facility' id='facility'>
<option selected='selected' disabled='disabled' value=''>Select facility</option>
</select>";
JQuery/AJAX
function getFacility(val) {
$.ajax({
type: "POST",
url: "getfacility.php",
data:'account_id='+val,
success: function(data){
$("#facility").html(data);
}
});
}
getfacility.php
//db connection..
if(!empty($_POST["account_id"])) {
$accountID = $_POST['account_id'];
$sql = "SELECT *, account.account_name FROM facility "
. "INNER JOIN account ON account.account_id = facility.account_id "
. "WHERE facility.account_id = '". $accountID ."'";
$data = mysqli_query($dbc, $sql);
echo "<option selected='selected' disabled='disabled' value=''>Select facility</option>";
while ($fRow = mysqli_fetch_array($data)) {
$facilityOptions .="<option value=\"".$fRow['facility_id']."\">" . $fRow['facility_name'] . "</option>";
}
$facilityDropDown=" <label>Facility: </label><br>
<select name='facility' id='facility'>
<option selected='selected' disabled='disabled' value=''>Select facility</option>
" . $facilityOptions . "
</select>";
}
Right now, when I make a selection on my first drop down, the second one does not populate with anything, where am I going wrong?

Make the changes in getfacility.php,
if your ajax showing 200 ok status and expected response in Network (Console)
//db connection..
if(!empty($_POST["account_id"])) {
$accountID = $_POST['account_id'];
$sql = "SELECT *, account.account_name FROM facility "
. "INNER JOIN account ON account.account_id = facility.account_id "
. "WHERE facility.account_id = '". $accountID ."'";
$data = mysqli_query($dbc, $sql);
echo "<option selected='selected' disabled='disabled' value=''>Select facility</option>";
while ($fRow = mysqli_fetch_array($data)) {
echo "<option value=\"".$fRow['account_id']."\">" . $fRow['account_name'] . "</option>";
}

Related

Build Combobox with Item Selected

Trying to create a combo box with the user's current value selected. I'm thinking my issue is with the apostrophe's and quotes - can anyone with a sharp eye help? Variable $MCI is created before any quotes/apostrophes and is functioning properly.
$MCI = '';
$MCI = $row['MobileCarrierID'];
echo '
<select name="MobileCarrierName">
<?php
$sql = mysqli_query("SELECT MobileCarrierID, MobileCarrierName FROM tblMobileCarrier ORDER BY MobileCarrierName;");
while ($row = mysqli_fetch_array($sql)){
$MCISelected = (' . $MCI . '==$row["MobileCarrierID"] ? " selected" : "");
echo "<option value=" . $row['MobileCarrierID'] . $MCISelected . ">" . $row['MobileCarrierName'] . "</option>";
}
?>
</select>';
Thank you!
You have
echo '
<select name="MobileCarrierName">
<?php
$sql=
which needs to be changed to
echo '<select name="MobileCarrierName">';
$sql=
Also
$MCISelected = (' . $MCI . '==$row["MobileCarrierID"] ? " selected" : "");
needs to be changed to
$MCISelected = ($MCI==$row["MobileCarrierID"])? " selected" : "";
And your mysqli_query is missing the database connection ie
mysqli_query($db,$query);
Finally, close off with
echo '</select>';
Your quotes and brackets are off and you've placed your selected variable inside your value in the option, a complete edited code should look something like...
<?php
echo '<select name="MobileCarrierName">';
$sql = mysqli_query($conn, "SELECT MobileCarrierID, MobileCarrierName FROM tblMobileCarrier ORDER BY MobileCarrierName;");
while ($row = mysqli_fetch_array($sql)){
$MCISelected = ($MCI==$row["MobileCarrierID"])? " selected" : "";
echo '<option '.$MCIselected.' value="'.$row["MobileCarrierID"].'">'.$row["MobileCarrierName"].'</option>';
}
echo'</select>';
Check out How to set an option from multiple options or array with different values to views as selected in select box using PHP for a guide on how it works
<?php
$sql = mysqli_query("SELECT MobileCarrierID, MobileCarrierName FROM tblMobileCarrier ORDER BY MobileCarrierName;");
?>
<select name="MobileCarrierName">
<?php
while ($row = mysqli_fetch_array($sql)){
$MCI = $row['MobileCarrierID'];
$MCISelected = ($MCI==$row["MobileCarrierID"]) ? " selected" : "";
echo "<option value=".$MCI." ".$MCISelected.">".$row['MobileCarrierName']."</option>";
}
?>
</select>
try this one

value of dropdown list from mysql

I'm trying to compose an estimate formula, and I stucked with value of dropdown list populated by MySQL.
The idea of this formula is when a user select a service from dropdown list and put the quantity in textfield the program will compute the price for the service.
The value of the prize is selected from MySQL table.
$query="SELECT $con_tent FROM services WHERE $id;
$con_tent= 'price'. '*'. $qunatity
But I don't know how to get the value from dropdwon list.
Probably with Ajax but still don't know how.
I solved this by modyfing code from http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html
<?php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_user, $db_password);
mysql_select_db($db_database) or die("unable to select database:" . mysql_error());
echo "<form action=licz.php method='post'>";
echo " <label for=\"select\"><select name=\"\" value=\"Select\" size=\"1\">";
$query = "SELECT * FROM uslugi ORDER BY id ASC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
global $ff;
$ajdi = $row['id'];
$nazwa = $row['nazwa'];
$options.= "<option value=\"$ajdi\" name=\"oko\">" . $nazwa . $ajdi;
}
echo "<option>";
echo $options;
echo "</option></select>";
echo " <input type=\"submit\" name=\"Submit\" value=\"Submit\">";
echo "</form>";
function wybor() {
global $id;
global $con_tent;
$var = 'price' . '*';
$quantity = 3;
//quantity will by from textfield but now it constant
$id_value = 1;
// here i need to make it dynamic
$id = "id={$id_value}";
$con_tent = $var . $quantity;
}
echo wybor();
$query = "SELECT $con_tent FROM services WHERE $id";
//query
if (!$query) Die("Unable to query: " . mysql_error());
$result = mysql_query($query);
if (!$result) Die("Unable to query: " . mysql_error());
$rows = mysql_num_rows($result);
for ($a = 0; $a < $rows; ++$a) {
$row = mysql_fetch_row($result);
echo $row[0] . " ";
echo $row[1] . " ";
echo $row[2] . " ";
echo $row[3] . "$br";
}
?>
You should apply ajax call to get value for database when there is a change in select box through calling a function on onchange event of javascript.
Read More for jquery AJAX
http://www.sitepoint.com/ajax-jquery/
http://www.tutorialspoint.com/jquery/jquery-ajax.htm

Find previously selected option in while loop

I'm trying to get a drop down menu to keep its selected value when the user hits submit, but it fails due to errors on the form.
I have a while loop returning values from a database to build the options for the drop down, but how do I echo "selected" on the right option?
I have tried if($district == $row["name"]) { echo "selected";} as you see below, but it doesn't work.
<?php
$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = 6 GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo '<option value="{$row["name"]}"'; if($district == $row["name"]) { echo "selected";} ; echo '>' . $row["name"] . "</option>";
}
?>
Sorry for the delay. None of the suggested answers worked for me. Any other ideas?
Can you try this,
<?php
$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = 6 GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
$district = $_REQUEST['name']; // You need pass the value you have been submitted
while ($row = mysql_fetch_array($result)) {
$selected ="";
if(trim($district) == trim($row["name"])) { $selected = "selected";}
echo '<option value="{$row["name"]}" '.$selected.' >' . $row["name"] . "</option>";
}
?>
Try this..
if($district == $row["name"])
{
echo "<option value='$district' selected>$district</option>";
}
I just found the answer. This is what I did:
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row["name"] . '"';
if($row["name"] == $district) { echo 'selected';} ;
echo '>' . $row["name"] . '</option>';
}
It seems to have been this line
echo '<option value="{$row["name"]}"';
that was causing the problem.

Set selected item in combobox to "please select..."

I'd like to add "Please select..." as the first option in my combobox. See code below - any suggestions?
Regards,
Peter
<?php
mysql_connect ("localhost", "username", "password");
mysql_select_db('mysqldb');
$sql = "SELECT data_id FROM projects";
$result = mysql_query($sql);
echo "<select name='data_id '>";
$sql[0] = 'Please select...';
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['data_id '] . "'>" . $row['data_id'] . "</option>";
}
echo "</select>";
?>
replace
$sql[0] = 'Please select...';
to this
echo '<option value="" disabled>Please select...</option>';
Why not just replace your $sql[0] = 'Please select...'; line (which by the way does nothing useful whatsoever) by this line:
echo "<option selected disabled>Please select...</option>";
The selected keyword is even optional if this is the first option you specify.

PHP multi option search query ....?

I'm trying with search box, I created a form as below:
<form method="post" action="search.php">
<select name="purpose">
<option value="" selected="selected">-any-</option>
<option value="For Sale">For Sale</option>
<option value="For Rent">For Rent</option>
</select>
<select name="type">
<option value="" selected="selected">-any-</option>
<option value="Bungalow">Bungalow</option>
<option value="Apartment">Apartment</option>
</select>
<select name="location">
<option value="" selected="selected">-any-</option>
<option value="Norway">Norway</option>
<option value="Itley">Itley</option>
</select>
<input type="submit" value="Search">
</form>
Search.php
I'm trying with these queries but getting problem:
$purpose=$_POST['purpose'];
$type=$_POST['type'];
$location=$_POST['location'];
If I put AND query like this:
SELECT * FROM test WHERE purpose='$purpose' AND location='$location' AND type='$type'
then it not filter one by one result its appear blank.
If I put OR query like this:
SELECT * FROM test WHERE purpose='$purpose' OR location='$location' OR type='$type'
Then it filter mix results.
I want if all selected it filter (purpose >> type >> location) AND if one selected then filter by this but exact result else show
Result not found!
EDIT Adding update made in comments:
I'm doing like this but it showing error:
$qry = "SELECT * FROM test WHERE 1=1";
if($purpose!="")
$qry .= " AND purpose='$purpose'";
if($location!="")
$qry .= " AND location='$location'";
if($type!="")
$qry .= " AND type='$type'";
while ($row = mysql_fetch_array($sql))
echo $row['purpose'];
echo $row['location'];
echo $row['type'];
I want if not match display result not found else it filter by all and one by one.
Put that after obtaining the variables:
$sql = array();
if (!empty($purpose)) {
$sql[] = "purpose='$purpose'";
}
if (!empty($type)) {
$sql[] = "type='$type'";
}
if (!empty($location)) {
$sql[] = "location='$location'";
}
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM test" . (!empty($sql)?: " WHERE " . $sql: '');
EDIT: After seeing your comments
First, you should make the connection to the database with the mysql_connect functions. Let's say, for example, that you have this piece of code:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
In the $link var now you have your mysql handle. This piece of code must go at the first of every page where you wanna use the mysql connection. Once you have the SQL sentence (in the code I first wrote, the $sql var), use this after:
$result = mysql_query($sql);
if (mysql_num_rows($result) === 0) {
echo 'Result not found';
}
while ($row = mysql_fetch_array($result)) {
echo $row['purpose'] . '<br/>';
echo $row['location'] . '<br/>';
echo $row['type'];
}
$qry = "SELECT * FROM test WHERE 1=1";
if($purpose!="")
$qry .= " AND purpose='$purpose'";
if($location!="")
$qry .= " AND location='$location'";
if($type!="")
$qry .= " AND type='$type'";

Categories