I want to populate dropdown value from mysql table.I used load event
in html page,but i don't know this code doesn't work.
HTML PAGE
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#select1").load("se2.php");
});
});
</script>
</head>
<body>
<select id="select1"></select>
<button>Get External Content</button>
</body>
</html>
se2.php
<?php
$dbhandle = mysql_connect("localhost","root","")
or die("Unable to connect to MySQL");
$selected = mysql_select_db("student",$dbhandle)
or die("Could not select examples");
$result1 = mysql_query("SELECT column1 FROM information");
while($row=mysql_fetch_array($result1))
{
if($row['column1']!=NULL)
{
echo "<option value='$row[column1]'>$row[column1]</option>";
}
}
?>
If you want to do the logic in the front end using jquery, you can follow this example :
jQuery: Best practice to populate drop down?
This way you can return your php array using json_encode() and in you jquery function you access it as an object, like in the above example.
change this
<select id="select1"></select>
to this
<div id="select1"></div>
and add the select tags to the php
$result1 = mysql_query("SELECT column1 FROM information");
echo "<select>";
while($row=mysql_fetch_array($result1))
{
if($row['column1']!=NULL)
{
echo "<option value='$row[column1]'>$row[column1]</option>";
}
}
echo "</select>";
and give the button an id
<button id="button">Get External Content</button>
In HTML instead of including <select> try this,
<div id="select1"></div>
And in php try this,
echo "<select>";
while($row=mysql_fetch_array($result1))
{
if($row['column1']!=NULL)
{
echo "<option value='$row[column1]'>$row[column1]</option>";
}
}
echo "</select>";
Related
I have two table ,
state where StCode, StateName
2.district where DistCode, StCode, DistrictName
My code for first Drop down
<td><label for="studentstate"></label>
<select name="studentstate" id="studentstate">
<?php
$con=mysql_connect("localhost","root","");
if(!$con)
{
die('could not connect:'.mysql_error());
}
mysql_select_db("db_loan",$con);
$sqlstr="select StCode,StateName from state";
$result=mysql_query($sqlstr);
while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['StCode'].'">'.$row['StateName'].'</option>';
}
echo $sccode=$row['StCode'];
?>
</select></td>
Now i have try following for second dropdownlist where i want to show district name
<div id="result">
<input type="button" value="Reload"></input>
<select name="studentdist" id="studentdist">
<?php
$con=mysql_connect("localhost","root","");
if(!$con)
{
die('could not connect:'.mysql_error());
}
mysql_select_db("db_loan",$con);
$sqlstr="select DistCode,DistrictName from district where StCode='$sccode'";
$result=mysql_query($sqlstr);
while($row=mysql_fetch_array($result))
{
echo '<option value="'.$row['DistCode'].'">'.$row['DistrictName'].'</option>';
}
// echo $sccode=$row['DistCode'];
?>
</select></td>
</div>
Now if i what i should do for reload my div when select first value from drop down list
Please if you know please tell me how to do it without using ajex or jquery
After read suggestion from mirza i have updated my code as follow but still there it is not working
</head>
<script type="text/javascript">
$("#studentstate").change(function()
{
$("#studentdist").load("pag1.php?choice=" + $("#studentstate").val());
});
</script>
<body>
you need some JQuery Basic to do this task
<script type="text/javascript">
$("#first-choice").change(function() {
$("#second-choice").load("getter.php?choice=" + $("#first-choice").val());
});
</script>
getter.php replace with your php page name and it will work
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
})
})
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
I made 2 dropdownlists which are filled from my database. In the first drop are countries and in the second are cities. When a user selects a country automatically in the second drop down appears all the cities from that country. The problem is that when I select another country all the page is refreshing and I want just that 2 drop down lists to do the refresh. I'm using Javascript and PHP. Here are the codes:
#$cat=$_GET['cat'];
$quer2=mysql_query("SELECT DISTINCT category,cat_id FROM category order by category");
if(isset($cat) and strlen($cat) > 0){
$quer=mysql_query("SELECT DISTINCT subcategory FROM subcategory where cat_id=$cat order by subcategory");
}else{$quer=mysql_query("SELECT DISTINCT subcategory FROM subcategory order by subcategory"); }
echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
while($noticia2 = mysql_fetch_array($quer2)) {
if($noticia2['cat_id']==#$cat){echo "<option selected value='$noticia2[category]'>$noticia2[category]</option>"."<BR>";}
else{echo "<option value='$noticia2[cat_id]'>$noticia2[category]</option>";}
}
echo "</select>";
echo "  ";
echo "<select name='subcat'><option value=''></option>";
while($noticia = mysql_fetch_array($quer)) {
echo "<option value='$noticia[subcategory]'>$noticia[subcategory]</option>";
}
echo "</select>";
and this is the Javascript code:
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='index.php?cat=' + val ;
}
I want that when I change the country the all page doesn't refresh only those 2 drop down lists. Any help will be much appreciated.
U can use Ajax for acheving this.
Pls check this link Populate select list
If U are using jquery use .ajax(). Example of jquery ajax select list populate is Jquery Ajax Select List Populate
You need to use ajax. A very rudimentary suggestion would be:
//self.location = '...' - removed
ajax('index.php?cat=' + val).done(function (result) {
//update select boxes
});
Try this
index.php
<!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" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".Select1").change(function()
{
var id=$(this).val();
var dataString = 'your_param='+ your_param;
$.ajax
({
type: "POST",
url: "select_2.php",
data: dataString,
cache: false,
success: function(html)
{
$(".Select2").html(html);
}
});
});
});
</script>
<title>Untitled Document</title>
</head>
<body>
<?php
include("config.php");
$sql="SELECT * FROM your_table";
$result2 = mysql_query($sql);
?>
<select class="Select1">
<option value=""></option>
<?php
while($row2 = mysql_fetch_array($result2))
{
?>
<option value="<?php echo $row2['your_value']?>"><?php echo $row2['your_value']?> </option>
<?php
}
?>
</select><br />
<select class="Select2"></select>
</body>
</html>
And in select_2.php
<?php
include('config.php');
if($_POST['your_param'])
{
$your_param=$_POST['your_param'];
$sql = mysql_query("SELECT * FROM yortable WHERE param = '".$your_param."'") or die(mysql_error());
while($row=mysql_fetch_array($sql))
{
$your_value=$row['your_param'];
echo '<option></option>';
echo '<option value="'.$your_value.'">'.$your_value.'</option>';
}
}
?>
Yep you're going to need to use AJAX in order to just update part of the page. The easiest way to use AJAX is through JQuery. Here's their API for AJAX.
I have MySQL tables looking like this:
regions table
id | region
-------------------
1 | Region1
2 | Region2
...
and schools table
region_id | school
-------------------
1 | schno1
1 | schno5
1 | schno6
2 | scho120
My page works like this: At first, page populates #regions select menu from db table named "regions". when user selects #region, the JS sends selected region's value to search.php. Server-side PHP script searches db table named "schools" for #region (previously selected menu) value, finds all matches and echoes them.
Now the question is, how can I hide #class and #school select menus, and show only error message "there is no school found in this region" if no matches are found? How to check if there's no result from search.php? I'm a beginner to JS.
My JavaScript looks like this: http://pastie.org/2444922 and the piece of code from form: http://pastie.org/2444929 and finally search.php: http://pastie.org/2444933
Update
I changed my JS but no success.
$(document).ready(function(){
$("#school").hide();
$("#class").hide();
searchSchool = function(regionSelect){
var selectedRegion = $("select[name*='"+regionSelect.name+"'] option:selected").val();
if (selectedRegion!='0'){
$.ajax({
type: "POST",
url : "core/code/includes/search.php",
data: "®ion_id="+selectedRegion,
success: function(result, status, xResponse){
if (result!=null){
$("#school").show();
$("#class").show();
$("#school").html(result);
}else{
$("#error").html("There is no school found in this region");
$("#school").html('');
$("#school").hide();
}
},
error: function(e){
alert(e);
}
});
}else{
$("#error").html('Please select a region first');
$("#school").html('');
$("#school").hide();
$("#class").hide();
}
}
});
You could try this
index.php :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Ajax With Jquery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
searchSchool = function(regionSelect){
var selectedRegion = $("select[name*='"+regionSelect.name+"'] option:selected").val();
if (selectedRegion!='0'){
$.ajax({
type: "POST",
url : "search.php",
data: "®ion_id="+selectedRegion,
success: function(result, status, xResponse){
alert(result);
if (result!=''){
$("#school").show();
$("#school").html(result);
}else{
$("#error").html("There is no school found in this region");
$("#school").html('');
$("#school").hide();
}
},
error: function(e){
alert(e);
}
});
}else{
$("#error").html('Please select a region first');
$("#school").html('');
$("#school").hide();
}
}
</script>
</head>
<body>
<?php
$username="root";
$password="";
$database="test";
mysql_connect('localhost',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM regions";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
echo "<b><center>Database Output</center></b><br><br>";
?>
<select name="region" id="region" onchange="searchSchool(this)">
<option value="0">Please select a Region</option>
<?php
while($data = mysql_fetch_array( $result ))
{
?>
<option value="<?php echo $data['id']?>"><?php echo $data['name']?></option>
<?php
}
?>
</select>
<select name="school" id="school"></select>
<span id="error"></span>
</body>
</html>
Search.php:
<?php
$username="root";
$password="";
$database="test";
mysql_connect('localhost',$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
if(isset($_POST['region_id'])) {
$query = "SELECT * FROM schools WHERE region_id='".$_POST['region_id']."'";
$result=mysql_query($query);
$num = mysql_numrows($result);
if ($num>0){
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
}
else{
return null;
}
}
mysql_close();
?>
Well i cannot exactly read through your full code but i can give you a mock up of what you might wanna do.
have both the dependant drop downs wrapped in a div.
<div id="dep1"></div>
<div id="dep2"></div>
Now in server side after making the validations if u find elements create a drop down and send it here or just send an error message.
<?
if($num>0) {
?>
<select>
<?
foreach($element as $ele) {
<option><?=$ele?></option>
}
?>
</select>
<?
} else {
?>
<div class="error">No regions found</div>
<? } ?>
Your js would look something like
$("#dep1").html(loadbar).load("mypage.php","region="+regionid);
I think the issue resides in your jQuery code on lines 27-30. There is no element with ID = cl_dropdown and the comma delimited makes it look for cl_dropdown inside of sch_dropdown.
My guess is that the second select used to have the id cl_dropdown at one point. If so, the HTML for it should look like this:
<select id="cl_dropdown" name="class">
You should also have an element for the message. According to the jQuery, you are supposed to have an #no_sch element but I don't see it.
<div id="no_sch"></div>
Then replace lines 27-30 with the following:
if (!results) {
$("#sch_dropdown").hide();
$("#cl_dropdown").hide();
$('#no_sch').show();
$('#no_sch').text('no matches found');
};