Building a dropdown based on another dropdown in php - php

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
})
})

Related

php ajax dependent dropdown not loading data from table

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
}
?>

Get text from dynamic dropdown and use it in another file

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.

Post value using ajax to function autocomplete

I have here a dropdown select and autocomplete function. What I need to do is to pass the selected value of dropdown to autocomplete.php to use in my query. Textbox value should depending on value from dropdown. If selected value is supplies, all supplies only value in textbox (like pencil or ballpen).
I used this Ajax in Dynamic Dropdown. How I can use this to pass the value in autocomplete.php?
Note: this Ajax was not connected in my autocomplete function. How I can use this ajax to pass the value to my autocomplete.php query.
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#sub').html(data);
}
});
});
</script>
Ajax.php
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<script>
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
</script>
Drop1
<?php
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main">
<option value="" disabled="disabled" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
Auto Complete <input id="tag" type="text">
Autocomplete.php
<?php
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["q"]);
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' GROUP BY id ORDER BY item" );
if($sql)
{
while($row=mysqli_fetch_array($sql))
{
echo $row['item']."\n";
}
}
?>
$('#sub').html(data); should be $('#tag').html(data);
You have not defined #sub element in your html code, when placing this
$('#sub').html(data);
After that your name of the page must be same, while your using getajax.php, and its not you have defined us

Dynamic Dependant Dropdown menu with ajax php mysql

I am attempting to make dynamic dropdown boxes a search tool to help narrow down display data from a mysql server. I am a decent php programmer but need help with the javascript and ajax.
The site currently consists of 3 pages: index_test.php, dropdown.php and dropdown2.php.
On index_test.php there are 4 dropdown menus that need to be populated with information. The first is populated with state names from a mysql table using php when the page loads. The second box is populated using .change() that references php code and and displays schools in the selected state from a mysql table.
The third box is supposed to then take the selected value from the second box and display the class names from the selected school to the user and that step is where the code is breaking. The php works when tested by submitting the form but I would like to be able to fill the last 2 boxes without a page refresh.
The format of the mysql tables are:
table schools: (school_id, schools, states)
table classes: (class_id, school_id, class_abrv, class_number)
Thank you for your help
The code for index_test.php:
<?php include_once("connect.php"); ?>
<html>
<head>
<title>ajax</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#state").change(function(){
var state = $("#state").val();
$.ajax({
type:"post",
url:"dropdown.php",
data:"state="+state,
success: function(data) {
$("#school").html(data);
}
});
});
$("#school").change(function(){
var state = $("#school").val();
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+school,
success: function(data) {
$("#classname").html(data);
}
});
});
});
</script>
</head>
<body>
<h1>Get Notes:</h1>
<br/>
<form action="dropdown2.php" method="post">
State: <select id="state" name="state">
<option>--Select State--</option>
<?php
$sql = "SELECT states FROM states";
$result = mysql_query($sql);
while ($output = mysql_fetch_array($result)) {
$state_name = $output['states'];
echo "<option value=\"$state_name\">$state_name</option>";
}
?>
</select>
<br/>
School: <select id="school" name="school">
<option>--Select School--</option>
</select>
<br/>
Class Name: <select id="classname" name="classname">
<option>--Select Class Name--</option>
</select>
<br/>
Class Number: <select id="classnumber" name="classnumber">
<option>Select Class Name</option>
</select>
<br/>
<input type="submit" value="Search" />
</form>
</body>
</html>
Dropdown.php:
<?php
include_once("connect.php");
$state=$_POST["state"];
$result = mysql_query("select schools FROM schools where states='$state' ");
while($school = mysql_fetch_array($result)){
echo"<option value=".$school['schools'].">".$school['schools']."</option>";
}
?>
Dropdown2.php
<?php
include_once("connect.php");
$school=$_POST['school'];
$result = mysql_query("SELECT school_id FROM schools WHERE schools='$school' ");
$school_id = mysql_fetch_array($result);
$id = $school_id['school_id'];
$classname = mysql_query("SELECT DISTINCT class_abrv FROM classes WHERE school_id='$id' ORDER BY class_abrv asc");
while($class = mysql_fetch_array($classname)){
echo"<option value=".$class['class_abrv'].">".$class['class_abrv']."</option>";
}
?>
in second ajax function you have assigned the school drop down box value to state variable but you pass the variable school to ajax post. So there is no school variable that is why you get error.
$("#school").change(function(){
var *state* = $("#school").val();
//above variable should be school.
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+*school*,
success: function(data) {
$("#classname").html(data);
}
});
});

dynamically updating select boxes with php mysql ajax

I am trying to populate an initial select box with results from mysql via php. Then I would like the second select box to update with additional information related to what was chosen in the first box.
Here I am selecting some campaign names, then in the second box i would like to update with the versions of the campaign stored in mysql.
here is the name script:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"> </script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#campaign").change(function(){
var campaign = $("#campaign").val();
$.ajax({
type:"post",
url:"getversion.php",
data:"campaign="+campaign,
success: function(data) {
$("#version").html(data);
}
});
});
});
</script>
</head>
<body>
Campaign :
<select name="campaign" id="campaign">
<option>-Select a Campaign-</option>
<?php
include "db_conn.php";
$result = mysql_query("SELECT campaign, time FROM dfa_data GROUP BY campaign");
while($row = mysql_fetch_array($result)){
echo "<option value=$row[campaign]>$row[campaign]</option>";
} ?>
</select>
Version :
<select name="version" id="version">
<option>-Select a Version-</option>
</select>
</body>
</html>
then there is another script that pulls in the second select box data, although it does not populate and I do not have any idea why.
<?php
include "db_conn.php";
$campaign = $_POST["campaign"];
$result = mysql_query("SELECT * FROM dfa_data where campaign='$campaign' GROUP BY time");
while($rowa = mysql_fetch_array($result)){
echo"<option value=$rows[time]>$rows[time]</option>";
}
?>
Can anyone show me what I am doing wrong and why the second select box will not populate. Thanks in advance.
Not sure if this is your issue, but it's probably AN issue. In your second script you have:
while($rowa = mysql_fetch_array($result)){
echo"<option value=$rows[time]>$rows[time]</option>";
}
You are fetching into $rowa, but trying to access $rows. Try this instead.
while($row = mysql_fetch_array($result)){
echo '<option value="'.$row['time'].'">'.$row['time'].'</option>';
}
I think rowa and rows are the errors. Try row instead of both

Categories