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
Related
I have made a simple php and jquery based program. In which when a page is open then I want to show all category data first and All is selected. And then when change category by dropdown then data will be display according to selected Category.
But using this change function of jquery how to do that.
Two files:
index.php file
<?php
$db = mysql_connect('localhost', 'root', 'root') or die("Could not connect database");
mysql_select_db('myproject', $db) or die("Could not select database");
$result = mysql_query("SELECT * from category");
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#select_category").change(function(){
var catid = $("#select_category option:selected").val();
$.ajax({
type : "post",
url : "product.php",
data: { id:catid },
success: function (response) {
var getres = $.parseJSON(response);
var results = "";
results += "<table border='1'>";
results += "<tr>"+
"<th>Product Name</th>"+
"<th>Category</th>"+
"<th>Publish</th>"+
"</tr>";
$.each(getres.data , function (key,value){
results += "<tr><td>" + value.product_name + "</td><td>" + value.publish + "</td><td>" + value.category + "</td></tr>";
});
results+= "</table>";
$(".result-container").html(results);
}
});
});
});
</script>
</head>
<body>
<select name="cat" id="select_category">
<option value="0">--All--</option>
<?php
while ($row = mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['cat_id'] ?>"><?php echo $row['cat_name'] ?></option>
<?php } ?>
</select><br><br><br>
<div class="result-container">
</div>
</body>
</html>
product.php file
$db = mysql_connect('localhost', 'root', 'root') or die("Could not connect database");
mysql_select_db('myproject', $db) or die("Could not select database");
$cat_id = $_POST['id'];
$query = "SELECT p.name AS product_name,CASE WHEN p.publish='yes' THEN '+' ELSE '-' END AS publish,c.cat_name AS categoryFROM product p LEFT JOIN category c ON c.cat_id = p.category";
if(!empty($cat_id)){
$query = $query. 'WHERE p.category='.$cat_id;
}
$sql = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}
$result=array('data'=>$rows);
echo json_encode($result);
You can do that by calling same ajax code on page load with empty category id.
<?php
$db = mysql_connect('localhost', 'root', 'testing') or die("Could not connect database");
mysql_select_db('myproject', $db) or die("Could not select database");
$result = mysql_query("SELECT * from category");
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function ajaxCall(catid = '') {
$.ajax({
type: "post",
url: "product.php",
data: { id: catid },
success: function(response) {
var getres = $.parseJSON(response);
var results = "";
results += "<table border='1'>";
results += "<tr>" +
"<th>Product Name</th>" +
"<th>Category</th>" +
"<th>Publish</th>" +
"</tr>";
$.each(getres.data, function(key, value) {
results += "<tr><td>" + value.product_name + "</td><td>" + value.publish + "</td><td>" + value.category + "</td></tr>";
});
results += "</table>";
$(".result-container").html(results);
}
});
}
$(document).ready(function() {
ajaxCall();
$("#select_category").change(function() {
var catid = $("#select_category option:selected").val();
ajaxCall(catid);
});
});
</script>
</head>
<body>
<select name="cat" id="select_category">
<option value="0">--All--</option>
<?php
while ($row = mysql_fetch_array($result)) {?>
<option value="<?php echo $row['cat_id']; ?>">
<?php echo $row['cat_name']; ?>
</option>
<?php } ?>
</select>
<br>
<br>
<br>
<div class="result-container"></div>
</body>
</html>
I want to Post Multiple values for foreach function because i have multiple dynamic textbox then how should i send the values in database??
how to write foreach function for dat..
the code below display 2 multiple textbox but didnt submit values in databse
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Hobby No. ' + counter + '</strong><br />'
+ '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />'
+'<strong>HolidayReason ' + counter + '</strong> '
+ '<input id="holidayreason_' + counter + '" name="holireason[]' + '" type="text" />'
);
});
});
</script>
<body>
<?php
if (isset($_POST['submit_val'])) {
if (($_POST['dynfields'])&& ($_POST['holireason'])) {
//$aaa=array($_POST['dynfields']);
foreach ($_POST['dynfields'] as $key=>$value)
{
$values = mysql_real_escape_string($value);
//$holireasons = mysql_real_escape_string($holireason);
$query = mysql_query("INSERT INTO my_hobbies (hobbies) VALUES ('$values')" );
}
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";
mysql_close();
}
?>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">
<div id="container">
<p id="add_field"><span>Click To Add Hobbies</span></p>
</div>
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
</body>
</html>
try this
<html>
<head>
<title></title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Hobby No. ' + counter + '</strong><br />'
+ '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />'
+'<strong>HolidayReason ' + counter + '</strong> '
+ '<input id="holidayreason_' + counter + '" name="holireason[]' + '" type="text" />'
);
});
});
</script>
<body>
<?php
if (isset($_POST['submit_val'])) {
if (($_POST['dynfields'])&& ($_POST['holireason'])) {
$no = count($_POST['dynfields']);
for ($i=0; $i <$no ; $i++) {
echo $_POST['dynfields'][$i]."<br>";
echo $_POST['holireason'][$i]."<br>";
$abc = mysql_real_escape_string($_POST['dynfields'][$i]);
$xyz = mysql_real_escape_string($_POST['holireason'][$i]);
$sql = "INSERT INTO my_hobbies (hobbies,Holidayreason) VALUES ('$abc','$xyz')";
mysql_query($sql);
}
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";
mysql_close();
}
?>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<div id="container">
<p id="add_field"><span>Click To Add Hobbies</span></p>
</div>
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
</body>
</html>
Use array_combine as follows.
foreach(array_combine($_POST['dynfields'] , $_POST['holireason']) as $dyn => $holi) {
$abc = mysql_real_escape_string($dyn);
$xyz = mysql_real_escape_string($holi);
$sql = mysql_query ("INSERT INTO my_hobbies (hobbies,Holidayreason) VALUES ('".$abc."','".$xyz."')");
}
100% works fine.
i am creating 2 dynamic drop list that the second one is based on the selection of the first but the problem is that the second one do not populate and i do not know where is the error can anyone help me ????
dbconfig.php
<?php
$host = "localhost";
$user = "*****";
$password = "****";
$db = "lam_el_chamel_db";
?>
select.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#district").attr("disabled","disabled");
$("select#governorate").change(function(){
$("select#district").attr("disabled","disabled");
$("select#district").html("<option>wait...</option>");
var id = $("select#governorate option:selected").attr('value');
$.post("select_district.php", {id:id}, function(data){
$("select#district").removeAttr("disabled");
$("select#district").html(data);
});
});
$("form#select_form").submit(function(){
var cat = $("select#governorate option:selected").attr('value');
var type = $("select#district option:selected").attr('value');
if(cat>0 && type>0)
{
var result = $("select#district option:selected").html();
$("#result").html('your choice: '+result);
}
else
{
$("#result").html("you must choose two options!");
}
return false;
});
});
</script>
</head>
<body>
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a governorate:<br />
<select id="governorate">
<?php echo $opt->ShowGovernorate(); ?>
</select>
<br /><br />
choose a district:<br />
<select id="type">
<option value="0">choose...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
</body>
</html>
select class.php
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "dbconfig.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowGovernorate()
{
$sql = "SELECT * FROM governorate";
$res = mysql_query($sql,$this->conn);
$governorate = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$governorate .= '<option value="' . $row['governorate_id'] . '">' . $row['governorate_name'] . '</option>';
}
return $governorate;
}
public function ShowDistrict()
{
$sql = "SELECT * FROM districts WHERE governorate_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$district = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$district .= '<option value="' . $row['district_id'] . '">' . $row['district_name'] . '</option>';
}
return $district;
}
}
$opt = new SelectList();
?>
select _type.php
<?php
include "select.class.php";
echo $opt->ShowDistrict();
?>
table structure
governorate :
governorate_id
governorate_name
districts:
district_id,
district_name,
governorate_id.
On select.php Page you used id for select tag is 'id="type"' which would be 'id = "district"' in select tag for choose a district : below text.
choose a district:<br />
<select id="type">
<option value="0">choose...</option>
</select>
By Below
choose a district:<br />
<select id="district">
<option value="0">choose...</option>
</select>
Rename page 'select_type.php' by 'select_district.php' Or do change in $.post ajax query. correct sending request page name by 'select_type.php'.
This should be changed in
from $sql = "SELECT * FROM districts WHERE governorate_id=$_POST[id]";
to $sql = "SELECT * FROM districts WHERE governorate_id=$_POST['governorate']";
also in select.php change
<select id='governorate'> to <select id='governorate' name='governorate'>
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();
}
dynamically adds more dropdownlist that is populated with data from MySQL to div on button click.
<div id="dynamicDiv"><p>
sqlconn();
$sql="SELECT column_name FROM table";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
echo "<select type=\"column_name\">";
for($i=0;$i<$num_rows;$i++){
$table = mysql_fetch_array($result);
echo "<option value='" . $table['column_name'] . "'>" . $table['column_name'] . "</option>";
}
echo "</select>";
mysql_close($con);
</div>
<input type="button" value="+ Data" onClick="addInput('dynamicDiv');">
the only method i know is by writing a script but i can't do any php scripting on the script (or i can?). need to query to populate added drop down list.
var counter = 1;
var limit = 15;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "whatever needs to be dynamically input on div";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
is there a workaround to populate the dropdownlist in the script? much appreciated!
You basically have 2 options
Create the HTML for the dropdown list when creating the page and do something like
as in
<script type=...>
var selecthtml='<?php echo $selecthtml; ?>'
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = selecthtml;
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
Or look at AJAX to populate your select.
The former is easier, the latter is cleaner.
**This is the actual way the test goes and Change according to your table and use it . It will work as you expected**
";
echo 'countStud ='.count($arrayData).';';
echo 'stud = '.json_encode($arrayData).';';
echo "";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
divCount =0;
function createDiv()
{
var divTag = document.createElement("div");
var studList ="";
studList += '<select id="BOX_'+divCount+'" name="BOX_'+divCount+'">';
studList += '<option value="">--- Select ---</option>';
for(i=0;i<countStud;i++){
studList += '<option value="'+stud[i].stud_id+'">'+stud[i].stud_name+'</option>';
}
studList += '</select>';
divTag.innerHTML = studList;
document.getElementById('dynamicElements').appendChild(divTag);
divCount++;
}
</script>
</head>
<body>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
<div id="dynamicElements"></div>
<input type="submit" value="Submit" />
</form>
<input type="button" onClick="createDiv()" value="Add"/>
</body>
</html>