I pull data from a MYSQL database to populate a Drop down
<td class="<?php print $Bank_ca_error;?>">Bank Name</td> <td> <select name="Bank" id="Bank" tabindex=24 style="color: <?php print $TextColour;?>"/> <option><?php print $_SESSION['Bank_ca'] ;?></option> <?php //Get Data to populate drop down $BankQuery = "SELECT BankName FROM tblbank ORDER BY BankName"; $BankResult = mysql_query ($BankQuery); While($nt=mysql_fetch_array($BankResult)) { print"<option $nt[BankName]>$nt[BankName]</option>"; } ?> </select> </td>
I would like based on the value selected populate a text input. So Basically Select the Bank from the List and have it autopopulate the Universal Branch Code in the text input.
I saw an example using Jquery, But I am a complete noob when it comes to this and I cannot get it to work properly
I added the following in the Head section
<script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery('#Bank').live('change', function(event) { $.ajax({ url : 'getData.php', type : 'POST', dataType: 'json', data : $('#myform').serialize(), success: function( data ) { for(var id in data) { $(id).val( data[id] ); } } }); }); }); </script>
I then Added this into the getData.php file
<?php include "../../../includes/dbinfo.inc"; //Connect to database mysql_connect($db_host, $db_username, $db_password); #mysql_select_db($db_database) or die("Unable to select database"); $BankName = $_POST['Bank']; // Selected Bank $query = "SELECT * FROM tblbank WHERE BankName ='{$BankName}'"; $result = mysql_query($query); $row = mysql_fetch_array($result) $BranchCode = $row['UniversalCode']; $arr = array( 'input#BranchCode' => $BranchCode ); echo json_encode( $arr ); ?>
and added the Following to around the inputs and dropdown concerned
<form id='myform'> </form>
I tried to use a solution elsewhere on this site but could not get it to work
Your assistance is greatly appreciated
If I understand correctly what you're trying to do, then you do not need ajax, try something like this
<?php
include "../../../includes/dbinfo.inc";
//Connect to database
mysql_connect($db_host, $db_username, $db_password); #mysql_select_db($db_database) or die("Unable to select database");
$res = mysql_query("SELECT UniversalCode, BankName FROM tblbank ORDER BY BankName");
while($row = mysql_fetch_assoc($res)) {
// associative array of banks
$banks[$row['UniversalCode']] = $row['BankName'];
}
?>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('#Bank').change( function() {
// enter in an empty field code of the selected bank
$('#UniversalCode').val( $(this).val() );
});
});
</script>
<td class="<?php print $Bank_ca_error;?>">Bank Name</td>
<td>
<select name="Bank" id="Bank" tabindex=24 style="color: <?php print $TextColour;?>"/>
<? foreach($banks as $code=>$name) { ?>
<option value="<?=$code?>"><?=$name?></option>
<? } ?>
</select>
<input value="" id="UniversalCode">
</td>
Related
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
}
?>
I am trying to get a value from a dropdown menu and pass it as a php variable and echo it (on the same page).
The dropdown displays the name of users, but select their username, which I want to echo. The purpose it to use the variable to perform other tasks, if I can echo it successfully.
I have used jquery and ajax to get the variable, without submitting the page. But I am unable to get the php variable.
I have read several examples, and used them, but somehow my code is not working.
Can anyone please suggest where is the mistake?
Here is my code:
Test2.php
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>
<select name="user" id="user" >
<option disabled selected value> - Select User - </option>
<?php
$sql_select = mysqli_query($conn,"SELECT username, surname, fname FROM user WHERE v_flag != 0 ORDER BY surname ASC ");
while ($result = mysqli_fetch_assoc($sql_select)){
$name = ($result['surname']. ', '.$result['fname']);
echo '<option value = " '.$result['username']. '">'.$name.'</option>';
}
?>
</select>
</td>
</tr>
</table>
<script type="text/javascript">
$(document).ready(function() {
$("#user").change(function() {
var user = $(this).val();
$.ajax({
url:"test2.php",
data:{username : user},
type:'POST',
success:function(response) {
$("#usermame").html(response);
}
});
});
});
</script>
<?php
if (isset($_POST['username'])){
$username = $_POST['username'];
if (!empty($username)){
echo 'You have selected user: '.$username ;
}
}
?>
<?php
if (isset($_GET['username'])){//only echo user name if requested from js do not include header or footer
$username = $_GET['username'];
if (!empty($username)){
echo 'You have selected user: '.$username ;
}
}else{//you can include here your headers
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>
<select name="user" id="user" >
<option disabled selected value> - Select User - </option>
<?php
$sql_select = mysqli_query($conn,"SELECT username, surname, fname FROM user WHERE v_flag != 0 ORDER BY surname ASC ");
while ($result = mysqli_fetch_assoc($sql_select)){
$name = ($result['surname']. ', '.$result['fname']);
echo '<option value = " '.$result['username']. '">'.$name.'</option>';
}
?>
</select>
</td> </tr> <tr><td> <span id="username">
<?php if (isset($_POST['username'])){//show if submitted from html form
$username = $_POST['username'];
if (!empty($username)){
echo 'You have selected user: '.$username ;
}
}
?> </span></td>
</tr>
</table>
<script type="text/javascript">
$(document).ready(function() {
$("#user").change(function() {
var user = $(this).val();
$.ajax({
url:"test2.php?username="+user,
success:function(response) {
$("#username").html(response);
}
});
});
});
</script>
<?php
//you can include here your footers
}
?>
Your success handler is printing the request content in a html element with id username that do not exists on the page (at least not on this snippet)
success:function(response) {
$("#usermame").html(response);
}
Try to make the POST request to a different file because, in your case, the printed content will include the select (and the db request) again.
I'm trying to create a program that when you select a state from the drop down menu, it will display the list of cities for that state in another drop down menu that you can select from. After you choose your city and state, you type in an address, hit submit, and it will display the full address on a new php file.
My issue at the moment is I can get the states displayed, but when the state is selected, it is not giving me the list of options for that city in the second drop down menu. Any help is appreciated, thanks!
You can view the behavior at this link
select.php
<head>
<link rel="stylesheet" type="text/css" href="select_style.css">
<script type="text/javascript" src="js/jquery.js"></script>
<!DOCTYPE html>
<form action = "display.php">
<script type="text/javascript">
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'fetch.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
});
}
</script>
</head>
<body>
<p id="heading">Address Generator</p>
<center>
<div id="select_box">
<select onchange="fetch_select(this.value);">
<option>Select state</option>
<?php
include ( "accounts.php" ) ;
( $dbh = mysql_connect ( $hostname, $username, $password ) )
or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db( $project );
$select=mysql_query("select state from zipcodes group by state");
while($row=mysql_fetch_array($select))
{
echo "<option>".$row['state']."</option>";
}
?>
</select>
<select id="new_select">
</select>
<div id='2'> </div>
<br><br>
<input type = text name="address">Address
<br><br>
<input type = submit>
</form>
fetch.php
<?php
include(accounts.php);
if(isset($_POST['get_option']))
{
( $dbh = mysql_connect ( $hostname, $username, $password ) )
or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db( $project );
$state = $_POST['get_option'];
$find=mysql_query("select city from zipcodes where state='$state'");
while($row=mysql_fetch_array($find))
{
echo "<option>".$row['city']."</option>";
}
exit;
}
?>
1)First of all your state option's value attribute is missing
echo "<option value='".$row["state"]."'>".$row["state"]."</option>";
2)Include(accounts.php); accounts.php should be enclosed by double quotes
3) And city option's value attribute is missing
echo "<option value='".$row["city"]."'>".$row["city"]."</option>";
4) Instead of echoing each time concatenate and echo finally like this
$options="";
while($row=mysql_fetch_array($find))
{
$options.= "<option value='".$row["city"]."' >".$row["city"]."</option>";
}
echo $options;
Warning!!!
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
I've modified your code a little. Tried to do it the elegant way. You had wrote too much of superfluous code. You didn't need a <form> element to perform the asked operation. Anyway below is the modified code.
<!DOCTYPE html>
<head>
<title>Address Generator</title>
</head>
<body>
<p id="heading">Address Generator</p>
<center>
<!-- <div id="select_box"> -->
<select name="select_box" id="select_box">
<?php
include ( "accounts.php" ) ;
( $dbh = mysql_connect ( $hostname, $username, $password ) ) or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db( $project );
$select=mysql_query("select state from zipcodes group by state");
while($row=mysql_fetch_array($select))
{
echo "<option>".$row['state']."</option>";
}
?>
</select>
<select id="new_select">
</select>
<div id='2'> </div>
<br><br>
<input type = text name="address">Address
<br><br>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#select_box').on('change', function() {
var state = $(this).val();
$.ajax({
url: 'fetch.php',
type: 'POST',
data: {state: state},
success: function(response)
{
var response = JSON.parse(response);
$('#new_select').find('option').remove();
var option = '';
$.each(response.cities, function(key, val) {
option = option + "<option value='" + val + "'>" + val + "</option>";
});
$('#new_select').append(option);
}
});
});
});
</script>
</body>
I've added Jquery before the end of </body> tag. This doesn't hinder your current code execution. However you could always preload it but that tactic is for later.
Since you didn't need any <form> element so I've completely removed it. You can always add it according to your convenience.
I'm running a loop on the cities array of the object response that I'm getting from fetch.php.
parsing the JSON data using JSON.parse() function.
You'll need to json_encode your json variable which will store the corresponding citites data.
I hope this helps. Any further queries are welcome too.
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
}
?>
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