Five Buttons One Dropdown List - php

I'm trying to populate a dropdown listbox with a set of five buttons. The first one works, however the other four do not, as of yet. If been looking around but due to inexperience I can't seem to put it together. Any help is appreciated. Thank you. Here is the code I have so far...incomplete.
mysql_select_db('Mydb');
$place = mysql_query("select * from tblRestaurants order by RestName ASC");
$cuisine = mysql_query("select * from tblCuisine order by CuisineName ASC");
$city = mysql_query("select * from tblCities order by CityName ASC");
$state = mysql_query("select * from tblStates order by StateName ASC");
$zipcode = mysql_query("select * from tblLocations order by ZipCode ASC");
while ($nt= mysql_fetch_assoc($place))
$arrData[] = $nt;
if(isset($_GET["ajax"]))
{
echo json_encode($arrData);
die();
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function displayPlace()
{
$.getJSON("Four.php?ajax=true", function(data) {
$.each(data, function(index, objRecord) {
var option=document.createElement("option");
option.value=objRecord.RestID;
option.text=objRecord.RestName;
$("#Doggie").append('<option value="' + objRecord.RestID + '">' + objRecord.RestName + '</option>');
});
});
}
function displayCuisine()
{
$.getJSON("Four.php?ajax=true", function(data) {
$.each(data, function(index, objRecord) {
var option=document.createElement("option");
option.value=objRecord.CuisineID;
option.text=objRecord.CuisineName;
$("#Doggie").append('<option value="' + objRecord.CuisineID + '">' + objRecord.CuisineName + '</option>');
});
});
}
</script>
<title>SEARCH</title>
</head>
<body>
<form>
<button type="button" onclick="javascript:displayPlace();">Place</button>
<button type="button" onclick="javascript:displayCuisine();">Cuisine</button>
<button type="button" onclick="javascript:displayCity();" >City</button>
<button type="button" onclick="javascript:displayState();">State</button>
<button type="button" onclick="javascript:displayZipCode();">Area</button>
<br />
<select name="Doggie" id="Doggie"></select>
<br />
</form>
</body>
</html>

Please modify your php code i have tried to explain this using some sample code
and pass one additional parameter of case in the ajax request and then it will work for you
$list['place'] = mysql_query("select * from tblRestaurants order by RestName ASC");
$list['cuisine'] = mysql_query("select * from tblCuisine order by CuisineName ASC");
foreach($list as $key=>$value){
while ($nt = mysql_fetch_assoc($list[$key]))
$list_array[$key] = $nt;
}
if(isset($_GET["ajax"]))
{
switch($_GET['case']){
case 'place':
echo json_encode($list_array['place']);
break;
case 'cuisine':
echo json_encode($list_array['cuisine']);
break;
}
die();
}

Related

Autocomplete search box from MySQL that displays multiple columns

I've been trying to make an autocomplete search box from a MySQL database that displays multiple columns of data when searching.(ie. Searching for an item #, at it displays the item number, manufacturer, and price)
Below is what I have currently done, which displays everything in one line separated by spaces. I would like to have a way to change the style for each column or make each result display in multiple lines if possible.
I'm a complete noob at this so any advice/resources would be awesome!
//ajax-db-search.php
<?php
require_once "db.php";
if (isset($_GET['term'])) {
$query = "SELECT DISTINCT MFG_Item_ID, MFG_Name, Price FROM H_Item_Master WHERE MFG_Item_ID LIKE '{$_GET['term']}%' LIMIT 5";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while ($user = mysqli_fetch_array($result)) {
$res[] = $user['MFG_Item_ID'] . " " . $user['MFG_Name'] . " " . $user['Price'];
}
} else {
$res = array();
}
//return json res
echo json_encode($res);
}
?>
//in my index.php
<!-- Topbar Search Catalog -->
<form
class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search">
<div class="input-group">
<input type="text" name="term" id="term" placeholder="Search Catalog" class="form-control"
aria-label="Search" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-primary" id="benchbutton" type="Submit">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
<script type="text/javascript">
$(function() {
$( "#term" ).autocomplete({
source: 'ajax-db-search.php',
});
});
</script>
You can override the default autocomplete style this way, so you can use html br tags and your own css stylesheet :
<script type="text/javascript">
$(function() {
$( "#term" ).autocomplete({
source: 'ajax-db-search.php',
select: function(event, ui) {
$("#term").val(ui.item.name);
return false;
}
})
.autocomplete("instance")._renderItem = function(ul, item) {
return $("<li class='each'>")
.append("<div class='item'><span class='upc'>" +
item.upc + "</span><br><span class='name'>" +
item.name + "</span><br><span class='price'>" +
item.price + "</span><br></div>")
.appendTo(ul);
};
});
</script>
Using the span's classes, you have full control on any attribute (upc, name and price) in CSS :
<style>
.each .item .upc{
font-style:italic;
color:blue;
}
</style>
Here is the final result :
Using this dataset :
PS : Here is how to use prepared statement to select and fetch datas from database :
if(isset($_GET['term']))
{
$term = '%' . $_GET['term'] . '%';
$sql = "SELECT * FROM items WHERE CONCAT(upc, name) LIKE ? LIMIT 5";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $term);
$stmt->execute();
$result = $stmt->get_result();
$items = [];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$items[] = $row;
}
}
$conn->close();
echo json_encode($items);
}

monitor and update variable number of fields in php form

I have an inventory form that pulls a variable number of rows of items from a database and creates a table/list of them, with input text boxes for quantity of cases( of 12) and individual items, and the script updates the total box with the sum of those two. I have it working if I put discrete sections of code in for each row, and have tried many while/for loops and the problem I think is the function is inside the loop and stops it from working. I looked at posts using .each() , but do not see any example that works with my setup. I went and answered a couple simple questions on here for others before posting this question, hoping to please the code gods ;-)
<form>
<div class="ex3">
<div class="headrow">
<div class="column">Batch</div>
<div class="column">Name</div>
<div class="column">UPC</div>
<div class="column">Cases</div>
<div class="column">Bottles</div>
<div class="column">Counted</div>
</div>
<?php
// grab all the pertinant entries from the database and create a row of entries for each one
$sql="SELECT BatchNum, BatchName, UPC FROM Batches WHERE CurrentBatch=1 AND UPC <> '' ORDER by BatchNum DESC";
$result = $mysqli->query($sql);
$numrows = $result->num_rows;
if ($result->num_rows > 0) {
$row_cnt = 0;
while ($row = $result->fetch_assoc()) {
echo '<div class=row>';
echo '<div class=column>'.$row['BatchNum'].'</div>';
echo '<div class=column>'.$row['BatchName'].'</div>';
echo '<div class=column>'.$row['UPC'].'</div>';
echo '<div class=column> <label for="CaseCount"></label><input type="text" inputmode="numeric" pattern="^\d{1,3}$" size="4" class="form-control" id="CaseCount'.$row_cnt.'" name="CaseCount'.$row_cnt.'" value="" ></div>';
echo '<div class=column> <label for="BottleCount"></label><input type="text" inputmode="numeric" pattern="^\d{1,3}$" size="4" class="form-control" id="BottleCount'.$row_cnt.'" name="BottleCount'.$row_cnt.'" value=""></div>';
echo '<div class=column> <label for="Counted"></label><input type="text" inputmode="numeric" pattern="^\d{1,8}$" size="8" class="form-control" id="Counted'.$row_cnt.'" name="Counted'.$row_cnt.'" value="" required></div>';
$row_cnt += 1;
echo "</div>";
}
}
?>
</div>
</li>
</ul>
</div>
</form>
<script>
// monitor the case and bottle count fields and update the counted field.
$(document).ready(function() {
$('#CaseCount0, #BottleCount0').on('input', function() {
var Counted0 = 0;
var value1 = $('#CaseCount0').val();
var value2 = $('#BottleCount0').val();
var Counted0 = (value1 * 12) + (value2 * 1);
$('#Counted0').val(Counted0);
});
$('#CaseCount1, #BottleCount1').on('input', function() {
var Counted1 = 0;
var value1 = $('#CaseCount1').val();
var value2 = $('#BottleCount1').val();
var Counted1 = (value1 * 12) + (value2 * 1);
$('#Counted1').val(Counted1);
});
$('#CaseCount2, #BottleCount2').on('input', function() {
var Counted2 = 0;
var value1 = $('#CaseCount2').val();
var value2 = $('#BottleCount2').val();
var Counted2 = (value1 * 12) + (value2 * 1);
$('#Counted2').val(Counted2);
});
// might be 20-30 of these lines
});
</script>
here is a script section I have tried, but could not get to work, I do not think it is good practice for the function to be inside the loop:
var numrows = <?php echo $numrows ?>-1;
var i;
$(document).ready(function() {
for(var i = 0; i <= numrows; i++) {
$("#CaseCount"+i).on('input', function() {
this["Counted"+i] = 0;
var value1 = $("#CaseCount" + i).val();
var value2 = $("#BottleCount" + i).val();
$("#Counted"+i).val((value1 * 12)+(value2 * 1));
});
}
});

AJAX success function not fetching data from MYSQL database

Apologies for similarities between this post and my previous one. I'd appreciate if someone could help me once again spot where I'm going wrong. Everything else appears to be working fine but what is puzzling me is the 'quiet' response on the AJAX success function. Nothing in the console either.
I've tested the JSON output with the json_encode and print_r functions and got the following - so I presume the JSON string should be ok to work with the AJAX:
Array
(
[proj_start_date] => 2017-04-17
[proj_end_date] => 2018-04-30
[wo_nbr_new] => 10002-06
)
{"proj_start_date":"2017-04-17","proj_end_date":"2018-04-30","wo_nbr_new":"10002-06"}
Below is the code for the main file:
<?php
include 'connect_db.php';
$sql = "SELECT * FROM projects ORDER BY proj_nbr";
$result = mysqli_query($connect,$sql);
$rowCount = mysqli_num_rows($result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add New Work Order</title>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Add New Work Order</h1>
<div id="forms-add" name="forms-add">
<form action="add_workorders.php" method="POST">
<label>Work Order Number (Auto-generated):</label>
<input type="text" id="wo_nbr" name="wo_nbr"size="8"maxlength="8" value = "" readonly style="float: right">
<br><br>
<fieldset>
<legend>Project Details</legend>
<label>Project Number:</label>
<select class= "selects" id="proj_nbr" name="proj_nbr" required onchange="">
<option value="">Select a project </option>
<?php
if($rowCount>0)
{
while ($row=mysqli_fetch_assoc($result))
{
echo '<option value="'.
$row['proj_id'].'">'.
$row['proj_nbr'].
' - '.
$row['proj_desc'].
' </option>';
}
}
else
{
echo '<option value="">Project not available</option>';
}
?>
</select>
<br><br>
<label>Start Date:</label>
<input type="text" id="proj_start_date" name="proj_start_date"size="8"maxlength="8" value = "" readonly style="float: right">
<br><br>
<label>End Date:</label>
<input type="text" id="proj_end_date" name="proj_end_date"size="8"maxlength="8" value = "" readonly style="float: right">
</fieldset>
<br><br>
<button type="submit" name="submit" >Save Work Order</button>
</form>
</div>
</body>
<script type="text/javascript" src="test_ajax.js"></script>
<script>
$(document).ready(function()
{
$('#proj_nbr').change(function()
{
var id=$('#proj_nbr').val();
//alert(id); //this works ok
if (id != '')
{
$.ajax({
url: "get_proj_nbrs2.php",
method:"POST",
data: {id:id}, //data to SEND to PHP file
dataType: "JSON",
success: function(output)
{
console.log(output); //this doesn't return anything in the console??
$('#wo_nbr').val(output.wo_nbr_new);
$('#proj_start_date').val(output.proj_start_date);
$('#proj_end_date').val(output.proj_end_date);
}
});
}
else
{
alert("Please select a Project");
}
});
});
</script>
</html>
And the following is the code in the PHP file:
<?php
include 'connect_db.php';
if (isset($_POST['id']) && !empty($_POST['id']))
{
$sql2 = "SELECT p.proj_nbr as wo_proj_nbr,p.start_date as proj_start_date,p.end_date as proj_end_date, MAX(w.wo_nbr) AS wo_nbr,
CASE WHEN SUBSTRING(MAX(w.wo_nbr),7,2)+1 <= 9 THEN CONCAT(p.proj_nbr,'-0',SUBSTRING(MAX(w.wo_nbr),7,2)+1)
ELSE CONCAT(p.proj_nbr,'-',SUBSTRING(MAX(w.wo_nbr),7,2)+1) END AS wo_nbr_new
FROM workorders as w
INNER JOIN projects as p on p.proj_id = w.proj_id
WHERE w.proj_id = '".$_POST['id']."'";
$result2 = mysqli_query($connect,$sql2);
while($row=mysqli_fetch_array($result2))
{
if($result2 ==true)
{
$proj_nbr = $row['wo_proj_nbr'];
$output['proj_start_date'] = $row['proj_start_date'];
$output['proj_end_date'] = $row['proj_end_date'];
if ($row['wo_nbr_new'] != NULL)
{
$output['wo_nbr_new'] = $row['wo_nbr_new'];
echo json_encode($output);
}
elseif($row['wo_nbr_new'] == NULL)
{
$output['wo_nbr_new'] = $proj_nbr."-01";
echo json_encode($output);
}
}
}
}?>
<?php
include 'connect_db.php';
if (isset($_POST['id']) && !empty($_POST['id']))
{
$result = array();
$sql2 = "SELECT p.proj_nbr as wo_proj_nbr,p.start_date as proj_start_date,p.end_date as proj_end_date, MAX(w.wo_nbr) AS wo_nbr,
CASE WHEN SUBSTRING(MAX(w.wo_nbr),7,2)+1 <= 9 THEN CONCAT(p.proj_nbr,'-0',SUBSTRING(MAX(w.wo_nbr),7,2)+1)
ELSE CONCAT(p.proj_nbr,'-',SUBSTRING(MAX(w.wo_nbr),7,2)+1) END AS wo_nbr_new
FROM workorders as w
INNER JOIN projects as p on p.proj_id = w.proj_id
WHERE w.proj_id = '".$_POST['id']."'";
$result2 = mysqli_query($connect,$sql2);
if($result->num_rows > 0)
{
while($row=mysqli_fetch_array($result2))
{
$proj_nbr = $row['wo_proj_nbr'];
$output['proj_start_date'] = $row['proj_start_date'];
$output['proj_end_date'] = $row['proj_end_date'];
if ($row['wo_nbr_new'] != NULL)
{
$output['wo_nbr_new'] = $row['wo_nbr_new'];
}
elseif($row['wo_nbr_new'] == NULL)
{
$output['wo_nbr_new'] = $proj_nbr."-01";
}
array_push($result,$output);
}
echo json_encode($result);
}
else
{
echo "no rows found";
}
}?>
You was echo each row so you will get result from success function in ajax as each separate sting. so it can't parse. hope this method will solve your problem.
Please confirm that you id value is not empty and matches to database field values as well. if so then change the 'id' to 'theid' (might be reserved word) in both the ajax e.g.
data: {theid:id}, //data to SEND to PHP file
and in php e.g.
if (isset($_POST['theid']) && !empty($_POST['theid'])) {
$sql2 = "SELECT p.proj_nbr as wo_proj_nbr,p.start_date as proj_start_date,p.end_date as proj_end_date, MAX(w.wo_nbr) AS wo_nbr,
CASE WHEN SUBSTRING(MAX(w.wo_nbr),7,2)+1 <= 9 THEN CONCAT(p.proj_nbr,'-0',SUBSTRING(MAX(w.wo_nbr),7,2)+1)
ELSE CONCAT(p.proj_nbr,'-',SUBSTRING(MAX(w.wo_nbr),7,2)+1) END AS wo_nbr_new
FROM workorders as w
INNER JOIN projects as p on p.proj_id = w.proj_id
WHERE w.proj_id = '".$_POST['theid']."'";
// code goes here
}
use type at method. method POST depends on jquery version
$.ajax({
url: "get_proj_nbrs2.php",
type:"POST",
data: {id:id}, //data to SEND to PHP file
dataType: "JSON",
success: function(output)
{
}
});

Drop down menu with jquery, php, mysql

I am fairly new to programming so if you can include explanations so I can learn as I go will be very appreciated.
Ok So I am making a drop down menu from sql tables and I am using php and Jquery. So far I have gotten my first sub menu which is states to populate from my country menu. Now I am getting confused on how to get my city menu to populate from my state menu.
Here is my main php file!
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#flip").click(function() {
jQuery("#panel").slideToggle("slow");
});
jQuery("#country").change(function() {
//jQuery("#address").val(jQuery("#courseid :selected").val());
var querystr = 'countryid='+jQuery('#country :selected').val();
jQuery.post("<?php echo plugins_url(); ?>/CountryStateCity Drop Down/ajax.php", querystr, function(data){
if(data.errorcode == 0){
jQuery('#statecbo').html(data.chtml)
//jQuery('#citydescr').append('<textarea name="citydescr" id="citydescr" cols="80" rows="3" maxlength="500"></textarea>')
}else{
jQuery('#statecbo').html(data.chtml)
}
}, "json");
});
});
</script>
<html>
<head>
<title>Dynamic Drop Down Menu</title>
</head>
<body>
<div class="wrap">
<h5> Country</h5>
<select id="country" name="country" required>
<option value="">--Select Country--</option>
<?php
$sql=mysql_query("SELECT * from country order by name");
while ($row=mysql_fetch_array($sql)) {
$countryID=$row['IDCountry'];
$countryname=$row['name'];
echo "<option value='$countryID'>$countryname</option>";
}
?>
</select>
</div>
<h5>State</h5>
<div class="wrap" id="statecbo">
</div>
<div class="wrap">
<h5>City</h5>
</div>
</body>
</html>
And here is my ajax.php file
$country_id = isset($_POST['countryid']) ? $_POST['countryid'] : 0;
if ($country_id <> 0) {
$errorcode = 0;
$strmsg = "";
$sql="SELECT * from state WHERE IDCountry = ". $country_id . " ORDER BY name;";
$result=mysql_query($sql);
$cont=mysql_num_rows($result);
if(mysql_num_rows($result)){
$chtml = '<select name="states" id="states"><option value="0">--Select State-- </option>';
while($row = mysql_fetch_array($result)){
$chtml .= '<option value="'.$row['IDState'].'">'.$row['name'].'</option>';
}
$chtml .= '</select>';
echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$chtml));
}else{
$errorcode = 1;
$strmsg = '<font style="color:#F00;">No States available</font>';
echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$strmsg));
}
}
So my next step would be to add a city menu that is populated by the state menu I just populated from the country menu. Sorry if that is confusing. Thanks!
Based of off jeroen response here is what I added to try and get the city drop down menu.
My main php file--
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#flip").click(function() {
jQuery("#panel").slideToggle("slow");
});
jQuery("#country").change(function() {
var querystr = 'countryid='+jQuery('#country :selected').val();
jQuery.post("<?php echo plugins_url(); ?>/CountryStateCity Drop Down/ajax.php", querystr, function(data){
if(data.errorcode == 0){
jQuery('#statecbo').html(data.chtml)
}else{
jQuery('#statecbo').html(data.chtml)
}
}, "json");
});
jquery(".wrap").on('change', '#states',function() {
var querystr = 'stateid=' +jQuery('#states :selected').val();
jquery.post("<?php echo plugins_url(); ?>/CountryStateCity Drop Down/ajax.php", querystr, function(data) {
if(data.errorcode ==0){
jQuery('#citycbo').html(data.chtml)
}else{
jQuery('#citycbo').html(data.chtml)
}
}, "json");
});
});
</script>
and my ajax.php file
$country_id = isset($_POST['countryid']) ? $_POST['countryid'] : 0;
if ($country_id <> 0) {
$errorcode = 0;
$strmsg = "";
$sql="SELECT * from state WHERE IDCountry = ". $country_id . " ORDER BY name;";
$result=mysql_query($sql);
$cont=mysql_num_rows($result);
if(mysql_num_rows($result)){
$chtml = '<select name="states" id="states"><option value="0">--Select State--</option>';
while($row = mysql_fetch_array($result)){
$chtml .= '<option value="'.$row['IDState'].'">'.$row['name'].'</option>';
}
$chtml .= '</select>';
echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$chtml));
}else{
$errorcode = 1;
$strmsg = '<font style="color:#F00;">No States available</font>';
echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$strmsg));
}
}
$state_id = isset($_POST['IDState']) ? $_POST['IDState'] : 0;
if ($state_id <> 0) {
$errorcode = 0;
$strmsg = "";
$sql="SELECT * from state WHERE IDState = ". $state_id . " ORDER BY name;";
$result=mysql_query($sql);
$cont=mysql_num_rows($result);
if(mysql_num_rows($result)){
$chtml = '<select name="city" id="city"><option value="0">--Select city-- </option>';
while($row = mysql_fetch_array($result)){
$chtml .= '<option value="'.$row['IDCity'].'">'.$row['name'].'</option>';
}
$chtml .= '</select>';
echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$chtml));
}else{
$errorcode = 1;
$strmsg = '<font style="color:#F00;">No city available</font>';
echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$strmsg));
}
}
You basically do the same thing you have done with the country / states.
However, you are using the jQuery change() function so that will not work with elements that were not on the page when that function was registered.
You can solve that by using event delegation:
jQuery(".wrap").on('change', '#states', function() {
// do your stuff
}
I have used the .wrap element as that is the one that wraps your form elements, but you could also use document for example.
And you can of course use the same method for what you have already, just change:
jQuery("#country").change(function() {
to:
jQuery(".wrap").on('change', '#country', function() {

Reset second jquery drop down select box when first is changed

I am using the following script to fetch records from my database and put them into select boxes using jquery, ajax and php. The select boxes are also styled and added features using Select 2
http://ivaynberg.github.io/select2/select-2.1.html#basics
If I select a customer from the first select box and then select a vehicle from the second box this works fine........if I then change my mind and select a different company, the vehicle box stays on the last reg and doesn't revert back to :
<option>Select A Customers Vehicle</option>
If I then click on the vehicle select box I can select the vehicles from the company and the 'ghost vehicle' from the last query vanishes, so it does work, its just when I change the company again I would like it just to reset the vehicle box back to its default again until I select a vehicle.
This is the Main Page :
<script src="js/jquery/jquery.js"></script>
<script src="js/jqueryui/js/jquery-ui.js"></script>
<link href="js/select2/select2.css" rel="stylesheet"/>
<script src="js/select2/select2.js"></script>
<script>
$(document).ready(function() { $("select").select2(); });
</script>
<?php
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
if (isset($_SESSION['key'])) {$sessionkey = $_SESSION['key'];}else {$sessionkey = '';}
if ($sessionkey == 'sbhjbKA2bsbhjbKA209bhjbKA2bsbhjbKA209KaXff19u0bsbhjbKA209KaXff19u9Ka'){
include 'connectmysqli.php';
echo '<link rel="stylesheet" href="css/template/template.css" />';
echo '<strong class="pagetitle">Add New Sale</strong>
';
$saleID = rand().rand();
$today = date("Y-m-d");
echo '<form method="post" action="addsalesubmit.php">';
echo '<input type="hidden" value="'.$saleID.'" name="saleID" id="saleID">';
echo '<input type="hidden" value="'.$today.'" name="date" id="date">';
?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Select test</title>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#customer').on('change', function (){
$.getJSON('select.php', {customerId: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['reg'] + ' - ' + data[x]['make'] + ' - ' + data[x]['model'] + '</option>';
}
$('#vehicle').html(options);
});
});
});
</script>
</head>
<body>
<br>
<select id="customer">
<option>Please Select / Search For A Customer</option>
<?php
$sql = <<<SQL
SELECT *
FROM `customers`
SQL;
if(!$result = $db->query($sql)){ die('There was an error running the query [' . $db->error . ']');}
while($row = $result->fetch_assoc()){
if ($row['bussinessname'] == ''){$name = $row['title'].' '.$name = $row['firstname'].' '.$name = $row['surname'];}else
{$name = $row['bussinessname'];}
echo '<option value="'.$row['customerID'].'">'.$name.'</option>';
}
echo '</select></p>';
?>
</select>
<br>
<br>
<select id="vehicle">
<option>Select A Customers Vehicle</option>
</select>
</body>
</html>
<?php
}
else
{echo '<h1 style="font-family:Verdana, Geneva, sans-serif; color:red;">Access Denied !</h1>';}
?>
This is the php script that does all the fetching :
<?php include 'connectmysqli.php'; ?>
<?php
$id = $_GET['customerId'];
$sql = 'SELECT * FROM vehicles WHERE customerID = ' . (int)$id;
$result = $db->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
$json[] = array(
'id' => $row['vehicleID'],
'reg' => $row['reg'],
'make' => $row['make'],
'model' => $row['model']
);
}
echo json_encode($json);
?>
On every call of the onchange first empty the second dropdown
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#customer').on('change', function (){
$('#vehicle').html("<option value=''>Select</option>");// add this on each call then add the options when data receives from the request
$.getJSON('select.php', {customerId: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['reg'] + ' - ' + data[x]['make'] + ' - ' + data[x]['model'] + '</option>';
}
$('#vehicle').html(options);
$("select").select2();
});
});
});
</script>
the following is not asked but i have to advice you that there are some additional errors in your code:
echo '</select></p>';
?>
</select>
there are two </select> and one </p> without a starting <p> at the end of your customer select box

Categories