I want to populate WILAYA dropList after a value is selected on MIKOA drop list. Here is what i did so far. But the drop down list is not populated onChange Event. what ım ı doıng wrong so far?
on first.php
<head>
<script type = "text/javascript">
function jazaWilaya (mkoa_value)
{
var xmlhttp = new XHMLHttpRequest ();
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("wilaya").innerHTML= xmlhttp.reponseText;
}
};
xmlhttp.open ("GET", "wilaya.php?mkoa="+mkoa_value, true);
xmlhttp.send ();
}
</script>
</head>
Inside the same file, here are the 2 drop down lists MKOA & WILAYA
Mkoa:
<select id="mkoa" name ="mkoa" onchange="jazaWilaya(this.value);" >
<option value = "chagua">Chagua</option>
<option>Arusha </option>
<option value = "dsm">Dar-es-Salaam</option>
<option value = "dodoma">Dodoma</option>
<option value = "kagera">Kagera </option>
<option value = "manyara">Manyara</option>
<option value = "mbeya">Mbeya</option>
<option value = "morogoro">Morogoro</option>
<option value = "mwanza">Mwanza</option>
<option value = "mtwara ">Mtwara</option>
<option value = "pwani">Pwani</option>
<option value = "shinyanga">Shinyanga </option>
<option value = "tabora">Tabora</option>
<option value = "tanga">Tanga</option>
<option value = "zanzibar">Zanzibar</option>
</select>
<br><br>
Wilaya:
<select id="wilaya" name="wilaya">
<option>Chagua</option>
<?php
while ($row = mysql_fetch_array($result))
{
?>
<option value = "<?=$row['wilaya_id']?>"><?php echo $row['wilaya_jina'];?></option>
<?php
}
?>
</select>
And this is the query code in another php file called wilaya.php
<?php
// put your code here
$con = mysql_connect("localhost", "root", "root");
if (!$con)
{
echo mysql_error();
}
$mkoa = mysql_real_escape_string($_REQUEST["mkoa"]);
mysql_select_db("dalaliOnline", $con);
$sql = "SELECT wilaya_jina FROM WILAYA WHERE mkoa_jina ='$mkoa' ";
$result =mysql_query($sql, $con);
?>
Correct your code in wilaya.php:
<?php
// put your code here
$con = mysql_connect("localhost", "root", "root");
if (!$con)
{
echo mysql_error();
}
$mkoa = mysql_real_escape_string($_REQUEST["mkoa"]);
mysql_select_db("dalaliOnline", $con);
$sql = "SELECT wilaya_jina FROM WILAYA WHERE mkoa_jina ='$mkoa' ";
$result =mysql_query($sql, $con);
while ($row = mysql_fetch_array($result))
{
?>
<option value = "<?=$row['wilaya_id']?>"><?php echo $row['wilaya_jina'];?></option>
<?php
}
?>
And remove following code from first.php file :
Wilaya: Should be
<select id="wilaya" name="wilaya">
<option>Chagua</option>
</select>
Instead of Wilaya:
<select id="wilaya" name="wilaya">
<option>Chagua</option>
<?php
while ($row = mysql_fetch_array($result))
{
?>
<option value = "<?=$row['wilaya_id']?>"><?php echo $row['wilaya_jina'];?></option>
<?php
}
?>
</select>
I am giving u one more example of a state and city when the user choose one state from the first select box than the 2nd select box appear with its corresponding city try this.
here is the state.php page.
<?php
mysql_connect("localhost","root","");
mysql_select_db("statename");
?>
<!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>
function showdetails(str)
{
var xmlhttp;
if (str==0)
{
alert("please select state name");
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("showresult").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","details.php?id="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
SELECT STATE:
:<select name="sid" id="sid" onchange="showdetails(this.value)">
<option value="0">Select State Name</option>
<?php
$sql="select sid,statename from state";
$qry=mysql_query($sql);
$num=mysql_num_rows($qry);
if($num>0)
{
while($res=mysql_fetch_array($qry))
{
?>
<option value="<?php echo $res['sid'];?>"><?php echo $res["statename"];?></option>
<?php
}
}
?>
</select>
CITY NAMES:
<div id=showresult></div>
</form>
</body>
</html>
The details.php page
mysql_connect("localhost","root","");
mysql_select_db("statename");
$id = $_REQUEST["id"];
$sql="select * from city where sid='$id'";
$qry=mysql_query($sql);
$num=mysql_num_rows($qry);
?>
<select name="cid" id="cid">
<option value="0">Select City Name</option>
<?php
if($num>0)
{
while($res=mysql_fetch_array($qry))
{
?>
<option value="<?php echo $res['cid'];?>"><?php echo $res["cityname"];?></option>
<?php
}
}
?>
</select>
Here is 2 tables here one is city table(cid, sid, cityname) another is state table(sid, state name) state table's sid is foreign key at sid city table
Following some updates to the question, here is my new answer. Original answer below is not relevant.
Your JavaScript can't do anything unless it has some output from your script to work with. A PHP variable is of no use to it. One solution would be to have wilaya.php create the new options for the select box using your original code for that:
<?php
$con = mysql_connect("localhost", "root", "root");
if (!$con)
{
// we don't want to output anything if something goes wrong, it'll mess the select up
die();
}
$mkoa = mysql_real_escape_string($_REQUEST["mkoa"]);
mysql_select_db("dalaliOnline", $con);
$sql = "SELECT wilaya_jina FROM WILAYA WHERE mkoa_jina ='$mkoa' ";
$result = mysql_query($sql, $con);
?>
<option>Chagua</option>
<?php
while ($row = mysql_fetch_array($result))
{
?>
<option value = "<?php echo $row['wilaya_id']; ?>"><?php echo $row['wilaya_jina']; ?></option>
<?php
}
?>
Then your JavaScript replaces the select box contents with the output of wilaya.php.
You're sending the data as a GET request but you have an if statement checking for a POST variable in wilaya.php, so if (isset ($_POST["mkoa"])) is evaluating to false and nothing is running in that file. Obviously without details of your database I don't know whether this is going to work when you fix that but seems to me that's the place to start. So you'll need to use GET instead of POST to check that this is set, eg:
if (isset ($_GET["mkoa"]))
{
// the rest of your code
}
(I assume below that code you have some output that the JS is using.)
Also, obligatory - the mysql_ extension is deprecated. Update to PDO or mysqli when convenient.
your wilaya.php should look like:
<?php
// put your code here
$con = mysql_connect("localhost", "root", "root");
if (!$con)
{
echo mysql_error();
}
$mkoa = mysql_real_escape_string($_REQUEST["mkoa"]);
mysql_select_db("dalaliOnline", $con);
$sql = "SELECT wilaya_jina FROM WILAYA WHERE mkoa_jina ='$mkoa' ";
$result =mysql_query($sql, $con);
?>
<option>Chagua</option>
<?php
while ($row = mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['wilaya_id']?>"><?php echo $row['wilaya_jina'];?></option>
<?php
}
?>
in your first.php file change
Wilaya:
<select id="wilaya" name="wilaya">
<option>Chagua</option>
</select>
Related
I have this onchange event on php, if the user choose an option, it fetched the data that is connected on it. However, the page refreshes and the choice of the user disappear. Also, I cannot insert the data to database. I've tried add a form method="post" to the form attribute, but unfortunately it cannot fetch the data.
Thankyou in advance.
<?php
$dsn = 'mysql:host=localhost;dbname=admin';
$username = 'root';
$password = '';
try{
// Connect To MySQL Database
$con = new PDO($dsn,$username,$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo 'Not Connected '.$ex->getMessage();
}
$gradeassign = '';
$sectionassign = '';
function getPosts()
{
$posts = array();
$posts[3] = $_POST['sectionassign'];
$posts[4] = $_POST['gradeassign'];
return $posts;
}
if(isset($_POST['addfac']))
{
$data = getPosts();
$insertStmt = $con->prepare('INSERT INTO
facultyagain(sectionnumber,gradelevelassign)
VALUES(:sectionassign,:gradeassign)');
$insertStmt->execute(array(
':sectionassign'=> $data[3],
':gradeassign'=> $data[4],
));
if($insertStmt)
{
echo 'Data Inserted';
}
}
?>
<html>
<head>
<title>Country</title>
</head>
<body>
<form action="trial.php">
Select Your grade
<select name="gradeassign" onchange="this.form.submit()">
<option value="" disabled selected>--select--</option>
<option value="1">Grade 1</option>
<option value="2">Grade 2</option>
<option value="europe">Europe</option>
</select>
<?php
require 'connection.php';
if(isset($_GET["gradeassign"])){
$gradeassign=$_GET["gradeassign"];
$sql = "SELECT sectionassign FROM sections WHERE gradeassign='$gradeassign'";
$result = $con->query($sql);
echo "<select>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='$row[sectionassign]'>" . $row["sectionassign"]. " </option>";
}
} else { echo "<B>0 Results</B>"; }
echo "</select>";
}
?>
<BR>
<button id="addfac" name="addfac">Add Faculty</button>
</form>
</body>
</html>
You can also store the value in a variable and check to see if the option matches the variable. For example:
<option value="" disabled>--select--</option>
<option value="1" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "1") echo "checked"; ?>>Grade 1</option>
<option value="2" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "2") echo "checked"; ?>>Grade 2</option>
<option value="europe" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "europe") echo "checked"; ?>>Europe</option>
The better way to do it would be to create the whole list with a loop. Bu this should work.
Database Table "Product" has a "Product_Code" and "Product_Name"
We have a form where we fill Product Data
Select options are fetched from Database table column "Product_Code"
<select name="Select_Product_Code" id="Select_Product_Code">
<option value="0">Product</option>
<?php
$con = mysqli_connect('localhost','user1db','userdb','1db');
if (!$con) { die('Could not connect: ' . mysqli_error($con)); }
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM Product";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
?>
<option value = "<?php echo($row['Product_Code'])?>" >
<?php echo($row['Product_Code']);
?>
</option>
<?php
}
?>
</select>
Without Form submit, Is there a way to show "Product_Name" in a Label or TextInput when "Product_Code" is selected ?
Edit , added ajax.
readproduct.php
<!DOCTYPE html>
<html>
<head>
<script>
function showProduct(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getproduct.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="products" onchange="showProduct(this.value)">
<option value="">Select </option>
<option value="1">0001</option>
<option value="2">0002</option>
<option value="3">0003</option>
<option value="4">0004</option>
</select>
</form>
<br>
<div id="txtHint"><b>list</b></div>
</body>
</html>
getproduct.php as follows
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','user1db','userdb','1db');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
echo "Connected";
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM Stock WHERE Product_Code = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo $row['Product_Name'];
}
mysqli_close($con);
?>
If we remove where clause, all products names are displayed,
with where clause, getproduct.php does not display Product_Names.
What we missed or did wrong?
You can populate an array inside your while loop that will be used later in a change listener for the select element like so:
<select name="Select_Product_Code" id="Select_Product_Code">
<option value="0">Product</option>
<?php
$con = mysqli_connect('localhost','user1db','userdb','1db');
if (!$con) { die('Could not connect: ' . mysqli_error($con)); }
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM Product";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
// here it adds a name with a key that matches the option-value
$names[$row['Product_Code']] = $row['Product_Name'];
?>
<option value = "<?php echo($row['Product_Code'])?>" >
<?php echo($row['Product_Code']);
?>
</option>
<?php
}
?>
</select>
<input type="text" id="out-text" value="The Name will appear here" />
<!-- then it populates the array with json_encode() to be used in the event-listener (both below) -->
<script type="text/javascript">
var names = <?php echo json_encode($names); ?>;
document.getElementById("Select_Product_Code").addEventListener(
'change',
function() {
document.getElementById("out-text").value = names[this.selectedIndex];
},
false
);
</script>
This is not the only way to do it, but its vanilla javascript/php, and here is a JSFiddle with the basic logic (minus the PHP part)
I have one table in my database called as company and inside company table there are 3 columns name Id,Company_Name and location.
I have two drop down list. First drop down list displaying only Company name and according to company name location will change in second drop down list.
I did some code but in second drop down i am getting all location name.
<?php
//$comp=$_POST['Company'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demo_db";
//open connection to mysql db
$connection = mysqli_connect($servername,$username,$password,$dbname) or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from company";// it displaying all company name in my first drop down list
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
if (isset($_POST['Company'])) {
$name=$_POST['Company'];
$sql = "select * from company where Company_name=$name";
}
$result_loc = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//close the db connection
mysqli_close($connection);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<select onchange='this.form.submit();' name="Company">
<option value="Select your Location1" disabled selected>Select your company</option>
<?php while($row = mysqli_fetch_array($result)):;?>
<option value="<?php echo $row[1];?>"><?php echo $row[1];?></option>
<?php endwhile;?>
</select>
<select>
<option value="" disabled selected>Select your location</option>
<?php while($row = mysqli_fetch_array($result_loc)):;?>
<option value="<?php echo $row[2];?>"><?php echo $row[2];?></option>
<?php endwhile;?>
</select>
</body>
</html>
To aid you in chaining SELECT menus using ajax the following might prove useful - you should be able to modify this to suit your db structure and naming conventions. You can run this "as-is" to see the results - hope it will prove useful.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) ){
$action=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
$id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT );
if( $action && $id && !is_nan( $id ) ){
$sql='select * from table where id=?';
/* etc ~ generic sql example only ! */
/* query db*/
/* process recordset and build menu data */
/*
demo response sent back to aajx callback
In reality this would be dynamically generated with
results from the db query above.
*/
for( $i=0; $i < 10; $i++ )echo "<option value='Location-$id-$i'>Location-$id-$i";
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>Dependent / Chained SELECT menus</title>
<script type='text/javascript' charset='utf-8'>
/* Basic Ajax function */
function ajax(m,u,p,c,o){
/*
m=Method,
u=Url,
p=Params,
c=Callback,
o=Options
*/
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
};
var params=[];
for( var n in p )params.push(n+'='+p[n]);
switch( m.toLowerCase() ){
case 'post': p=params.join('&'); break;
case 'get': u+='?'+params.join('&'); p=null; break;
}
xhr.open( m.toUpperCase(), u, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( p );
}
/* Callback function to populate second menu */
function createmenu(r,o,h){
/*
r=response
o=options ( sent by ajax function )
h=response headers
*/
o.menu.innerHTML=r;
}
function bindEvents(){
/* Get references to the two dropdown menus */
var oSelCompany=document.querySelectorAll('select[name="Company"]')[0];
var oSelLocation=document.querySelectorAll('select[name="Locations"]')[0];
/* Assign an `onchange` event listener */
oSelCompany.onchange=function(e){
var method='post';
var url=location.href;
/* the parameters to send to the PHP script */
var params={
'action':'getmenu',
'id':this.options[ this.options.selectedIndex ].value
};
/* Options to pass to the ajax callback */
var opts={
menu:oSelLocation
};
/* make the ajax request */
ajax.call( this, method, url, params, createmenu, opts );
}.bind( oSelCompany );
}
document.addEventListener( 'DOMContentLoaded', bindEvents,false );
</script>
<style type='text/css' charset='utf-8'>
select {padding:1rem;width:300px;}
</style>
</head>
<body>
<form method='post'>
<select name='Company'>
<option value=1>One
<option value=2>Two
<option value=3>Three
<option value=4>Four
<option value=5>Five
</select>
<select name='Locations'></select>
</form>
</body>
</html>
I have created a Demo for you. suppose you have company name and company has multiple location Example (id,name,location) :1,TCS,Banglore 2,TCS,Hyderabad
<?php
/*database connection*/
$con = mysqli_connect("localhost","root","root","search");
?>
<script>
function test(name)
{
// new file name f1.php
var strURL = "f1.php?name="+name;
var ax=new XMLHttpRequest();
ax.onreadystatechange = function()
{
if(ax.readyState==4){
document.getElementById("myid").innerHTML = ax.responseText;
}
}
ax.open("GET",strURL, true);
ax.send(null);
}
</script>
<?php
$sql= mysqli_query($con,"select * from company GROUP BY name ");
//print_r($sql);
?>
<select>
<option value="0">select company name</option>
<?php while ( $row = mysqli_fetch_array($sql))
{
?>
<option onclick="test('<?php echo $row["name"]; ?>');" id="<?php echo $i++."der" ;?>"> <?php echo $row["name"]; ?></option>
<?php }
?>
</select>
<div id="myid"></div>
Now Create a new file f1.php where you can run another mysql query to send the name of company you have selected by test function.here is the code
<?php
$con = mysqli_connect("localhost","root","root","search");
if(isset($_GET['name']))
{
$name = $_GET['name'];
}
$sql= mysqli_query($con,"select * from company where name='$name'");
?>
<select name="city">
<option>Select location</option>
<?php while ($row = mysqli_fetch_array($sql))
{ ?>
<option value=<?php echo $row['location']?>><?php echo $row['location']?></option>
<?php } ?>
</select>
I want to display the Mysql table Filed values in selectbox. I tried the following code to display.
But it normally display the specified field values in echo function and not in select box. I don't know where I mistake.
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee");
while($row = mysql_fetch_assoc($get))
{
echo ($row['Emp_id']."<br/>");
}
<html>
<body>
<form>
<select>
<option value = "<?php echo($row['Emp_id'])?>" ><?php echo($row['Emp_id']) ?></option>
</select>
</form>
</body>
</html>
Also the field values must be display in ascending order. How to achieve..
<?php
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee ORDER BY Emp_id ASC");
$option = '';
while($row = mysql_fetch_assoc($get))
{
$option .= '<option value = "'.$row['Emp_id'].'">'.$row['Emp_id'].'</option>';
}
?>
<html>
<body>
<form>
<select>
<?php echo $option; ?>
</select>
</form>
</body>
</html>
PS : On a sidenote, please stop using mysql_* functions. Take a look at this thread for the reasons.
You can easily do it like this
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee");
<html>
<body>
<form>
<select>
<option value="0">Please Select</option>
<?php
while($row = mysql_fetch_assoc($get))
{
?>
<option value = "<?php echo($row['Emp_id'])?>" >
<?php echo($row['Emp_id']) ?>
</option>
<?php
}
?>
</select>
</form>
</body>
</html>
You have to use while loop to display option in select box. try this ...
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee order by Emp_id");
<html>
<body>
<form>
<select>
<?php
while($row = mysql_fetch_assoc($get))
{
?>
<option value="<?php echo $row['Emp_id']; ?>"><?php echo $row['Emp_id']; ?></option>
<?php
}
?>
</select>
</form>
</body>
</html>
<?php
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee");
?>
<html>
<body>
<form>
<select>
<?php
while($row = mysql_fetch_assoc($get)){?>
<option value = "<?php echo($row['Emp_id'])?>" ></option>
<?php } ?>
</select>
</form>
</body>
<?php
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$res=mysql_query("SELECT Emp_id FROM Employee");
?>
<html>
<body>
<form>
<select>
<?php
while ($row = $res->fetch_assoc())
{
echo '<option value=" '.$row['id'].' "> '.$row['name'].' </option>';
}
?>
</select>
<form>
</body>
</html>
There a few tips to offer that will condense the code block for this task -- too many to just comment under the accepted answer.
Tested Code:
if (!$con = new mysqli("localhost", "root", "root", "Time_sheet")) {
echo "Database Connection Error: " , $con->connect_error; // don't show actual error in "production" stage
} elseif (!$result = $con->query("SELECT Emp_id FROM Employee ORDER BY Emp_id")) {
echo "Syntax Error: " , $con->error; // don't show actual error in "production" stage
} else {
echo "<select>";
foreach ($result as $row) {
echo "<option>{$row['Emp_id']}</option>";
}
echo "</select>";
}
The if line is both declaring $con and checking it for a falsey return value in one step.
Never provide the raw connection or query errors to your users. It is okay during development, but you don't want strangers to have access to critical/informative errors that your server will provide. This is a basic best practice for security.
The elseif line is both declaring $result and checking it for a falsey return value in one step.
The else block will process the zero or more rows of data that were generated as a result of the successful SELECT query.
The mysqli result is "traversable" which means you can iterate it using foreach() and enjoy direct access to the row data via associative keys. PHP Manual Reference Another StackOverflow Post
When writing an array element into a literal string via interpolation, it is good practice (though not always necessary) to wrap the element in curly braces. This will often trigger helpful highlighting in IDEs and ensure that the characters that follow the array are not accidentally coupled to the variable name itself.
You ONLY need to write a value attribute inside of the <option> tag IF the value is different from text between the opening and closing tags (<option>the text in here</option>). Form submissions and javascript implementations will all work the same if you omit the redundant value attribute.
If you DO wish to submit a different value in the select field rather than the text, here is what the syntax can look like:
echo "<option value=\"{$row['Emp_id']}\">{$row['Emp_name']}</option>";
If you want to write a selected attribute on one of the options based on a pre-existing variable (e.g. $selected_id), it can look like this:
echo "<option" , ($row['Emp_id'] == $selected_id ? " selected" : "") , ">{$row['Emp_name']}</option>";
If you wanted to combine the two previous processes, it can look like this:
echo "<option value=\"{$row['Emp_id']}\"" , ($row['Emp_id'] == $selected_id ? " selected" : "") , ">{$row['Emp_name']}</option>";
I am trying to populate second dropdown list based on first dropdown list selection using Ajax, jQuery, PHP and MySQL. The problem is the options in second dropdown list just appears in one line (all options in one line)!
I was hoping the while loop inside the results.php could handle this but it seems not. How can I fix this issue?
Here is my code:
<html>
<body>
<?php
$mysqli = new mysqli('localhost', 'root', '', 'chain');
if ($mysqli->connect_errno)
{
die('Unable to connect!');
}
else
{
$query = 'SELECT * FROM Cars';
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
?>
<p>
Select a Car
<select id="selectCar">
<option value="select">Please Select From The List</option>
<?php
while($row = $result->fetch_assoc())
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['title']; ?></option>
<?php
}
?>
</select>
</p>
<select>
<option value="select">Please Select From The List</option>
<option id="result"></option>
</select>
<?php
}
else
{
echo 'No records found!';
}
$result->close();
}
else
{
echo 'Error in query: $query. '.$mysqli->error;
}
}
$mysqli->close();
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#selectCar').change(function()
{
if($(this).val() == '') return;
$.get(
'results.php',
{ id : $(this).val() },
function(data)
{
$('#result').html(data);
}
);
});
});
</script>
</body>
</html>
In the PHP result I have:
<?php
$mysqli = new mysqli('localhost', 'root', '', 'chain');
$resultStr = '';
$query = 'SELECT * FROM models WHERE carID='.$_GET['id'];
if ($result = $mysqli->query($query))
{
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$resultStr.= '<option value="'.$row['id'].'">'.$row['model'].'</option>';
}
}
else
{
$resultStr = 'Nothing found';
}
}
echo $resultStr;
?>
You should edit your script into this..
<select id="result">
<option value="select">Please Select From The List</option>
</select>
You are setting $('#result').html(data); in the main file.
result should be the id of the HTML select element, you used it as id for the an option element.
(You are appending the values into the option element, which doesn't create new HTML elements, but they should be inserted into the select element.)