Dropdown selected value in second dropdownlist - php

I want to selected value from "list_cust_name" and want to pass it to another query to get the list of "list_cust_city". This list will show city of the customer which is selected from "list_cust_name". My table contains cust_id,cust_name,cust_city_cust_state.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function() {
$('#list_cust_name').change(function(){
$.ajax({
url:'city.php',
data:{cust_name:$( this ).val()},
success: function( data ){
$('#list_cust_city').html( data );
}
});
});
});
</script>
<label style="color:#000">Name </label>
<?php $data_name = mysql_query("SELECT DISTINCT cust_name FROM customer_db ORDER BY cust_name");?>
<select id="list_cust_name" name="list_cust_name">
<?php while($fetch_options_name = mysql_fetch_assoc($data_name)) { ?>
<option value="<?php=$fetch_options_name['cust_name']; ?>"><? php=$fetch_options_name['cust_name']; ?></option>
<?php } ?>
</select>
<select id="list_cust_city" name="list_cust_city"></select>
city.php
<?php
include('dbconnect.php');
db_connect();
$cust_name1=$_GET['cust_name'];
$data_city = mysql_query('SELECT DISTINCT cust_city FROM customer_db WHERE cust_name="'.$cust_name1.'" ORDER BY cust_city');
while($fetch_options_city = mysql_fetch_assoc($data_city)) {
?>
<option value="<?php=$fetch_options_city['cust_city'];?>"><?php=$fetch_options_city['cust_city'];?></option>
<?php
}
?>

I removed the id="list_cust_city" from the select, put it for a div that contains the select, the made the ajax return a full Select and put it inside that div. And added mysql_real_escape_string for the $GET to protect from mysql injection. You should consider starting to use mysqli or PDO as mysql* is deprecated.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function() {
$('#list_cust_name').change(function(){
$.ajax({
url:'city.php',
data:{cust_name:$( this ).val()},
success: function( data ){
$('#list_cust_city').html( data );
}
});
});
});
</script>
<label style="color:#000">Name </label>
<?php $data_name = mysql_query("SELECT DISTINCT cust_name FROM customer_db ORDER BY cust_name");?>
<select id="list_cust_name" name="list_cust_name">
<?php while($fetch_options_name = mysql_fetch_assoc($data_name)) { ?>
<option value="<?php=$fetch_options_name['cust_name']; ?>"><? php=$fetch_options_name['cust_name']; ?></option>
<?php } ?>
</select>
<div id="list_cust_city">
<select name="list_cust_city"></select>
</div>
city.php
<?php
include('dbconnect.php');
db_connect();
$cust_name1=mysql_real_escape_string($_GET['cust_name']);
$data_city = mysql_query("SELECT DISTINCT cust_city FROM customer_db WHERE cust_name='$cust_name1' ORDER BY cust_city");
?>
<select name="list_cust_city">
<?php
while($fetch_options_city = mysql_fetch_assoc($data_city)) {
?>
<option value="<?php=$fetch_options_city['cust_city'];?>"><?php=$fetch_options_city['cust_city'];?></option>
<?php
}
?>
</select>

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.

Select row table using ajax and php

I have a drop menu that includes some category every category has their own subcategory i want to show them buy selecting category name
but it's not working, did i miss something or am i doing it completely wrong?
<script type="text/javascript">
$(function() {
$("#error").hide();
$("#category").change(function(){
$("#error").hide();
var category = $("#category").val();
if (category == "") {
$("#error").show();
return false;
}
var data = $("#form").serialize();
$.ajax({
type:"POST",
url:"index.php",
data:data,
success: function(){
}
});
return false;
});
});
</script>
<form id="form" name="form">
<label for="category" id="error">Empty</label>
<select name="category" id="category">
<option></option>
<option value="News">News</option>
<option value="Items">Items</option>
<option value="Updates">Updates</option>
</select>
</form>
<?php
include("connect.php");
if(!empty($_POST['category'])){
$sql=$con->prepare("SELECT * FROM categorys WHERE category=:category ");
$sql->bindparam(":category",$_POST['category']);
$sql->execute();
while($r=$sql->fetch()){
echo $r['subcategory'];
}
}
?>
SomePage.php
<form id="form" name="form">
<div id='category'>
<label for="category" id="error">Empty</label>
<select name="category" id="category">
<option></option>
<option value="News">News</option>
<option value="Items">Items</option>
<option value="Updates">Updates</option>
</select>
</div>
<div id='subcategory'>
</div>
</form>
<script>
$('#category').change(function(){
var CatName= $('#category').val();
$.ajax({url:"AjaxSelectCategory.php?CatName="+CatName,cache:false,success:function(result){
$('#subcategory').html(result);
}});
});
</script>
Create New Page AjaxSelectCategory.php
[NOTE: If you want to change this page name. Change in <script></script> tag too. Both are related.]
<?php
include("connect.php");
if(!empty($_GET['CatName']))
{
$sql=$con->prepare("SELECT * FROM categorys WHERE category=:category ");
$sql->bindparam(":category",$_GET['CatName']);
$sql->execute();
?>
<select name='subcategory'>
<?php
while($r=$sql->fetch())
{?>
<option value="<?php echo $r['subcategory'];?>"><?php echo $r['subcategory'];?></option>
</select>
<?php }
}?>
Try like this,
$.ajax({
type:"POST",
url:"get_subcategory.php",
data:data,
success: function(data){
alert(data)// this will have the second dropdown. add to desired place in your view.
}
});
In get_subcategory.php
$sql = "Select * from table_name where catregory = ".$_POST'category'];
// execute the query.
$sub = "<select name='sub-category'>";
foreach(result from database as $row) {
$sub .= "<option value='$row->id'>$row->name</option>";
}
$sub .= "</select>";
echo $sub;

Select dropdown item and redirect to different page

My Code:
select name="accttype">
<?php foreach($query as $row)
{
$act=$row->accounttype;
?>
<option value="<?php echo$act;?>"><?php echo$act;?></option>
<?php
}
?>
</select>
When I select the dropdown list I want to to redirect different functions to load different pages, like:
<option value="<?php echo site_url('Controller_n/function'><?php echo$act;?></option>
Is this possible?
Check this sample:
<select id="accttype" name="accttype">
<?php foreach($query as $row)
{
$act=$row->accounttype;
?>
<option value="<?php echo $act ?>"><?php echo $act ?></option>
<?php } ?>
</select>
<script>
$(function(){
// bind change event to select
$('#accttype').on('change', function () {
var url = $(this).val(); // get selected value
if (url) { // require a URL
window.location = url; // redirect
}
return false;
});
});
</script>
Give a id to your select like below
<select id="accttype">
<?php foreach($query as $row)
{
$act=$row->accounttype; ?>
<option value="<?php echo$act;?>"><?php echo$act;?></option>
<?php } ?>
</select>
// add jquery library if you not added already
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#accttype').change(function(){
window.location = $(this).val();
});
});
</script>
Hope it will help you.

selected item in query fro dropdown list in php

Here is my code I made a script to get values in "list_cust_city" from selected item in "list_cust_name" through query in php. I didnt get any values in "list_cust_city" for city. I made city.php.
<script>
$('#list_cust_name').change(function(){
alert("heyyy");
$.ajax({
url:'city.php',
data:{cust_name:$( this ).val()},
success: function( data ){
$('#list_cust_city').html( data );
}
});
});
</script>
<label style="color:#000">Name </label>
<?php
$query_name = "SELECT DISTINCT cust_name FROM customer_db ORDER BY cust_name"; //Write a query
$data_name = mysql_query($query_name); //Execute the query
?>
<select id="list_cust_name" name="list_cust_name">
<?php
while($fetch_options_name = mysql_fetch_assoc($data_name)) { //Loop all the options retrieved from the query
$customer=$fetch_options_name['cust_name'];
?>
<option value="<?php echo $fetch_options_name['cust_name']; ?>"><?php echo $fetch_options_name['cust_name']; ?></option>
<?php
}
?>
</select>
city.php
<body>
<?php
include('dbconnect.php');
db_connect();
$cust_name1=$_GET['cust_name']; //passed value of cust_name
$query_city = "SELECT DISTINCT cust_city FROM customer_db WHERE cust_name='$cust_name1'ORDER BY cust_city"; //Write a query
$data_city = mysql_query($query_city); //Execute the query
while($fetch_options_city = mysql_fetch_assoc($data_city)) { //Loop all the options retrieved from the query
?>
<option value="<?php echo $fetch_options_city['cust_city']; ?>"><?php echo $fetch_options_city['cust_city']; ?></option>
<?php
}
?>
</body>
You must use document ready because the DOM isn't load.
$( document ).ready(function() {
$('#list_cust_name').change(function(){
alert("heyyy");
$.ajax({
url:'city.php',
data:{cust_name:$( this ).val()},
success: function( data ){
$('#list_cust_city').html( data );
}
});
});
});
PHP uses . to concat strings. Change your query to:
$query_city = 'SELECT DISTINCT cust_city FROM customer_db WHERE cust_name="'.$cust_name1.'"ORDER BY cust_city';
Also add this to your first php file:
<select id="list_cust_city" name="list_cust_city"></select>
Here's full code.
php 1:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function() {
$('#list_cust_name').change(function(){
$.ajax({
url:'city.php',
data:{cust_name:$( this ).val()},
success: function( data ){
$('#list_cust_city').html( data );
}
});
});
});
</script>
<label style="color:#000">Name </label>
<?php $data_name = mysql_query("SELECT DISTINCT cust_name FROM customer_db ORDER BY cust_name");?>
<select id="list_cust_name" name="list_cust_name">
<?php while($fetch_options_name = mysql_fetch_assoc($data_name)) { ?>
<option value="<?php=$fetch_options_name['cust_name']; ?>"><?php=$fetch_options_name['cust_name']; ?></option>
<?php } ?>
</select>
<select id="list_cust_city" name="list_cust_city"></select>
city.php:
<?php
include('dbconnect.php');
db_connect();
$cust_name1=$_GET['cust_name'];
$data_city = mysql_query('SELECT DISTINCT cust_city FROM customer_db WHERE cust_name="'.$cust_name1.'" ORDER BY cust_city');
while($fetch_options_city = mysql_fetch_assoc($data_city)) {
?>
<option value="<?php=$fetch_options_city['cust_city'];?>"><?php=$fetch_options_city['cust_city'];?></option>
<?php
}
?>

Categories