I have been trying to create a form with dynamic dropdown list fetching data from MYSQL. My database is fine without errors.
The first category of dropdown is working fine but I am wondering why my 2nd dropdown is not working. I just cant trace any error in the code and yet this is happening. here's my code:
Code for dynamic dropdown form :
<?php
include_once "connection.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>Dropdown Ajax</title>
</head>
<body>
<div class="country">
<label>Country</label>
<select name="country" onchange="getId(this.value);">
<option value="">Select Country</option>
//populate value using php
<?php
$query = "SELECT * FROM country";
$results=mysqli_query($con, $query);
//loop
foreach ($results as $country){
?>
<option value="<?php echo $country["cid"];?>"><?php echo $country["country"];?></option>
<?php
}
?>
</select>
</div>
<div class="city">
<label>City</label>
<select name="city" id="cityList">
<option value=""></option>
</select>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-
16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous">
</script>
<script>
function getId(val){
//We create ajax function
$.ajax({
type: "POST",
url: "getdata.php",
data: "cid="+val,
success: function(data){
$(#cityList).html(data);
}
});
}
</script>
</body>
</html>
Database connection code :
<?php
$con = mysqli_connect("localhost", "root", "kensift", "tuts");
//Check connection
if(mysqli_connect_errno()){
echo "Failed to connect:".mysqli_connect_errno();
}
?>
Code for 2nd dynamic dropdown :
<?php
include_once "connection.php";
if (!empty($_POST["cid"])) {
$cid = $_POST["cid"];
$query="SELECT * FROM city WHERE cid=$cid";
$results = mysqli_query($con, $query);
foreach ($results as $city){
?>
<option value="<?php echo $city["cityId"];?>"><?php echo $city["city"];?>
</option>
<?php
}
}
?>
These three code parts are in different files.
I think your code is correct except forgot the quotations id "#cityList" .
It should be
$("#cityList").html(data);
I think your problem might be here:
foreach ($results as $country){
?>
<option value="<?php echo $country["cid"];?>"><?php echo
$country["country"];?></option>
<?php
}
Try and use this instead:
foreach ($results as $country){
echo'<option value="'.$country["cid"].'">'.
$country["country"].'</option>';
}
Related
I'm trying to insert values input from the user in a form into my database.
I am trying to create 2 drop down lists, with the first deriving the options for the second. For example the first drop down list for Faculty, with the second drop-down list containing the schools within the selected faculty.
I am also then wanting to insert the gathered information into my database however I can focus on that after getting the drop-down's correct first.
My register page is on one page with the getSchool.php on a different file, I have a feeling the connection between the two could be my issue.
The register.php is below. This is the page the form is on
<?php
session_start();
include('dbConnect.php');
$queryStr=("SELECT * FROM faculty");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<html>
<head>
<TITLE>Faculty & School</TITLE>
<head>
<!-- Help for code to create dynamic drop downs -->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"
type="text/javascript"></script>
<script>
function getFaculty(val) {
$.ajax({
type: "POST",
url: "getFaculty.php",
data:'facultyID='+val,
success: function(data){
$("#schoolList").html(data);
}
});
}
function selectFaculty(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>
</head>
<body>
<div class="frmDronpDown">
<div class="row">
<label>Faculty:</label><br/>
<select name="faculty" id="facultyList" class="demoInputBox"
onChange="getFaculty(this.value);">
<option value="">Select Faculty</option>
<?php
foreach($results as $faculty) {
?>
<option value="<?php echo $faculty["facultyID"]; ?>"><?php echo
$faculty["facultyName"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<form action="addBlood.php" method="post">
<label>Test:</label><br/>
<select name="test" id="test-list" class="demoInputBox">
<option value="">Select Test</option>
</select>
</div>
</div>
<label>Result:</label><input class="input" name="result" type="text"><br>
<label>Date:</label><input class="input" name="date" type="date"><br>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
Below is the getSchool.php which gets all the schools
<?php
include('dbConnect.php');
if(!empty($_POST["facultyID"])) {
$queryStr=("SELECT * FROM school WHERE facultyID = '" . $_POST["facultyID"]
. "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<option value="">Select School</option>
<?php
foreach($results as $school) {
?>
<option value="<?php echo $school["schoolID"]; ?>"><?php echo
$school["schoolName"]; ?></option>
<?php
}
}
?>
Thanks in advance for any feedback and help.
Simon
url: "getFaculty.php",
data:'facultyID='+val,
success: function(data){
$("#schoolList").html(data);
Where is the #schoolList element ? Why getFaculty.php? Should it not be getSchool.php ?
First, just to re-iterate what was already mentioned, update your getFaculty() to get getSchool() and make sure it points to getSchool.php.
Now, you need to create a div following your first drop-down with an id schoolList.
<div class="row" id="schoolList"></div>
Now, update your getSchool.php so that it generates the full form/selection. Something along the lines of:
<?php
include('dbConnect.php');
if(!empty($_POST["facultyID"])) {
$queryStr=("SELECT * FROM school WHERE facultyID = '" . $_POST["facultyID"]
. "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<label>Schools:</label><br/>
<select name="schoolSelect" id="schoolSelect" class="demoInputBox">
<option value="">Select School</option>
<?php
foreach($results as $school) {
?>
<option value="<?php echo $school["schoolID"]; ?>"><?php echo
$school["schoolName"]; ?></option>
Once you've got those ideas down, you'll have to make sure you have the full flow of your page the way you want it. Then follow similar standards for posting any inputs to the php page you use for database manipulation.
As noted in earlier posts, this solution still leaves you vulnerable to injection. That's for another post, another day.
Hey im trying to create a dynamic dropdown list using PHP and AJAX. Its worth mentioning that im using visual composer on my wordpress site. So i have to make it a shortcode for visual composer.
Here is currently what ive got.
function dropdownmenu() {
include_once "connection.php";
?>
<div class="make">
<label>Make</label>
<select name="makelist" onchange="getId(this.value);">
<option value="">Select Make</option>
<?php
$query = "select distinct(Make) from websitemasterlist order by Make ASC";
$results = mysqli_query($conn, $query);
foreach($results as $info) {
?>
<option value="<?php echo $info[Make]; ?>"><?php echo $info[Make]; ?></option>
<?php
}
?>
</select>
</div>
<div class="model">
<label>Model</label>
<select name="model" id="modellist">
<option value="">Select Model</option>
</select>
</div>
<script src="code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
function getId(val){
$.ajax({
type: "POST",
url: "getdata.php",
data: "make="+val,
success: function(data){
$("#modellist").html(data);
}
});
}
</script>
<?php
}
add_shortcode('dropdownform','dropdownmenu');
?>
I think the error is somewhere in the ajax. because my ajax is weak.
here is the code for the secondary dynamic dropdown
<?php
include_once "connection.php";
if (!empty($_POST["make"])) {
$make = $_POST["make"];
echo $make;
$query = "SELECT distinct(Model) FROM websitemasterlist where Make=$make";
$results = mysqli_query($conn, $query);
foreach ($results as info2){
?>
<option value="<?php echo info2["Model"]; ?>"><?php echo info2["Model"]; ?></option>
<?php
}
}
?>
The first dropdown works. but the second dropdown doesn't show any choices when i make a choice on the first dropdown. Any help would be appreciated thank you. Its also worth mentioning that when i try to echo the make .... i dont see the make. so im pretty sure the ajax portion is messed up.
The errors I'm getting from the console
I have a form where the 1st select box is required. Depending on the selection, a different table will be used as a source for the query to populate a 2nd select box. Then depending also on the 1st selection a 3rd select box may or may not be necessary. I have designed the form to initially show 3 select boxes, but the user would have to know to skip the 2nd select box in some cases. This is confusing at the least. As an example:
If None is selected for Company, then both the Cemetery & Section select boxes would have to shown (Section being dependent on Cemetery selected). If XYZ Company is selected, then only the Section select box would need to be seen / selected (as the Cemetery is Company specific):
<script>
function getCemetery(val) {
$.ajax({
type: "POST",
url: "get_cemetery.php",
data:'company_name='+val,
success: function(data){
$("#cemetery-list").html(data);
}
});
}
Here is the code of the form:
<body>
<div class="frmDronpDown">
<div class="row">
<label>Company:</label><br/>
<select name="company" id="company-list" class="demoInputBox" onChange="getCemetery(this.value);">
<option value="">Select Company</option>
<?php
foreach($results as $company) {
?>
<option value="<?php echo $company["name"]; ?>"><?php echo $company["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Cemetery:</label><br/>
<select name="cemetery" id="cemetery-list" class="demoInputBox" onChange="getSection(this.value);">
<option value="">Select Cemetery</option>
<?php
foreach($results as $cemetery) {
?>
<option value="<?php echo $cemetery["name"]; ?>"><?php echo $cemetery["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Section:</label><br/>
<select name="section" id="section-list" class="demoInputBox">
<option value="">Select Section</option>
</select>
</div>
</div>
</body>
And here is the additional php code the is called within the script:
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["company_name"])) {
if (($_POST["company_name"]<>"None") && ($_POST["company_name"]<>"Other")) {
$sql="SELECT name, available FROM compsections WHERE cname = '".$_POST["company_name"]."'"." ORDER by available desc;";
$result = mysql_query($sql) or die ( mysql_error());
$row = mysql_fetch_row($result);
$section = $row[0]; // best choice to use if auto fill
$query="SELECT * FROM compsections WHERE cname = '".$_POST["company_name"]."'"." ORDER by available desc;";
$results = $db_handle->runQuery($query);
echo '<option value="">Select Section</option>';
}else{
$query ="SELECT * FROM cemeteries";
$results = $db_handle->runQuery($query);
echo '<option value="">Select Cemetery</option>';
}
foreach($results as $cemetery) {
?>
<option value="<?php echo $cemetery["name"]; ?>"><?php echo $cemetery["name"]." - ".$cemetery["available"]; ?></option>
<?php
}
}
?>
Edit:
Thank you for telling me about .hide and .show. I have looked up examples and what I can find uses a button click. Would you show an example of using them in an php if..else?
Thank you in advance.
Russ
I used the following:
<script>
function wholesection() {
$( "#whole-section" ).slideUp( "fast", function() {
});
}
</script>
AND
echo '<script>',
'wholesection();',
'</script>'
;
I have a form that pulls some dropdown data from an existing db. I've been working on a second dropdown that references the first to get more specific information from a different DB, however it looks like my code is broken somewhere. The first dropdown is populated fine but when i choose a "Manager" the Site dropdown goes blank, I even lose the "Select Site" option.
Any help would be appreciated.
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function getSite(val) {
$.ajax({
type: "POST",
url:"get_site.php",
data:'manager_id='+val,
success: function(data){
$("#site-list").html(data);
}
});
}
</script>
html/php
Manager<br/>
<select name="manager_id" onChange="getSite(this.value);">
<option value="">Select Manager</option>
<?php
$results = mysql_query("SELECT * FROM _managers");
while ($row_unit = mysql_fetch_array($results)){
?>
<option value="<?php echo $row_unit["id"]; ?>"><?php echo $row_unit["company"]; ?></option>
<?php
}
?>
</select>
<br/><br/>
Site<br/>
<select name="site_id" id="site-list">
<option value="">Select Site</option>
</select>
get_site.php
<?php
include('includes/connect-db.php');
if(!empty($_POST["manager_id"])) {
$manager_id = $_POST["manager_id"];
$results = mysql_query("SELECT * FROM _sites WHERE manager_id = $manager_id");
?>
<option value="">Select Site</option>
<?php
while ($row_site = mysql_fetch_array($results)){
?>
<option value="<?php echo $row_site["id"]; ?>"><?php echo $row_site["site_name"]; ?></option>
<?php
}
}
?>
As per discussion in comment.
I made the adjustment but still not getting my values from the
"get_site.php" file. Although now the "Select Site" stays in the site
dropdown.
Assuming you are getting proper data from MySQL server do some changes in get_site.php as below.
get_site.php
<?
include 'includes/connect-db.php';
if ((!empty($_POST["manager_id"])) && (isset($_POST["manager_id"])))
{
$manager_id = $_POST["manager_id"];
$results = mysql_query("SELECT * FROM _sites WHERE manager_id = '{$manager_id}'");
$options = "<option value=''>Select Site</option>";
while ($row_site = mysql_fetch_assoc($results))
{
$options .= "<option value='{$row_site['id']}''>{$row_site['site_name']}</option>";
}
return $options; // I personally prefer to echo using json_encode and decode it in jQuery
}
?>
Above code should give you the data you want.
Hope this solves your issue.Do comment if you are having any difficulties.
Ok below I will link a screenshot to show you what I'm working with so far.
In the left box I was to fill it with a list of 'EventIDs' which are the primary key on my database table.
When one of these IDs is selected I want the 'EventName' from the same table to appear in the box to the right.
https://gyazo.com/79e5e49bd288838c8ce1ae54fe245494
The problem so far is that the Event name is showing in the left select box and I'm not sure how to make it fetch data from the table when selected and to output in the text box. Hope that makes sense
Here is my code:
<!DOCTYPE html>
<html>
<head> </head>
<body>
<?php include 'login.php';?>
<select name="EventID">
<option value="">Select Event ID</option>
<?php
$result1 = mysqli_query($dbconnect, "SELECT EventID, EventName FROM event");
while($row1 = mysqli_fetch_assoc($result1)) {
?>
<option value="<?php echo $row1['EventID']; ?>"><?php echo $row1['EventName']; ?></option>
<?php
// End while loop.
}
?>
</select>
Event Name: <input name="EventName" type="text">
</body>
<html>
<!DOCTYPE html>
<html>
<head> </head>
<script>
function choice1(select) {
document.getElementById("EventName").value = select.options[select.selectedIndex].value;
}
</script>
<body>
<?php include 'login.php';?>
<select name="EventID" onchange="choice1(this)">
<option value="">Select Event ID</option>
<?php
$result1 = mysqli_query($dbconnect, "SELECT EventID, EventName FROM event");
while($row1 = mysqli_fetch_assoc($result1)) {
?>
<option value="<?php echo $row1['EventName']; ?>"><?php echo $row1['EventID']; ?></option>
<?php
// End while loop.
}
?>
</select>
Event Name: <input name="EventName" id="EventName" type="text">
</body>
<html>