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
Related
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 create a dropdown list to select State which is dependent on the another dropdown list Country.
Based on the Country selected from the first list, the second dropdown list should display corresponding states of the country.
For both the dropdown list I need to fetch values from the SQL server database.
Here is the code am trying:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.17.custom.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$("#country").change(function(){
var country=$("#country").val();
$.ajax({
type:"post",
url:"getcity.php",
data:"country="+country,
success:function(data){
$("#city").html(data);
}
});
});
});
</script>
</head>
<body>
Country :
<select name="country" id="country">
<option>-select your country-</option>
<?php
include "dbconfig.php";
$sql = "SELECT [CountryId],[Country] from Country order by [Country]";
$result=sqlsrv_query($conn,$sql);
while($country = sqlsrv_fetch_array($result)){
echo "<option value = $country[CountryId]>$country[Country]</option>";
} ?>
</select>
City :
<select name="city" id="city">
<option>-select your city-</option>
</select>
</body>
</html>
Below is the getcity.php code :
<?php
include "dbconfig.php";
$country=$_POST["country"];
$sql= "select [StateID],[State] from State where CountryId='$country'";
$result=sqlsrv_query($conn,$sql);
while($city=sqlsrv_fetch_array($result)) {
echo"<option value='$city[StateID]'>$city[State]</option>";
}
?>
I made database connection code in the file dbconnection.php and it is working fine, successfully connected with the database.
When I run this code I am not able to get the dropdown list of states after selecting the country. The code doesn't return any error but dropdown list of state not appear after selecting the country.
I am attempting to make dynamic dropdown boxes a search tool to help narrow down display data from a mysql server. I am a decent php programmer but need help with the javascript and ajax.
The site currently consists of 3 pages: index_test.php, dropdown.php and dropdown2.php.
On index_test.php there are 4 dropdown menus that need to be populated with information. The first is populated with state names from a mysql table using php when the page loads. The second box is populated using .change() that references php code and and displays schools in the selected state from a mysql table.
The third box is supposed to then take the selected value from the second box and display the class names from the selected school to the user and that step is where the code is breaking. The php works when tested by submitting the form but I would like to be able to fill the last 2 boxes without a page refresh.
The format of the mysql tables are:
table schools: (school_id, schools, states)
table classes: (class_id, school_id, class_abrv, class_number)
Thank you for your help
The code for index_test.php:
<?php include_once("connect.php"); ?>
<html>
<head>
<title>ajax</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#state").change(function(){
var state = $("#state").val();
$.ajax({
type:"post",
url:"dropdown.php",
data:"state="+state,
success: function(data) {
$("#school").html(data);
}
});
});
$("#school").change(function(){
var state = $("#school").val();
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+school,
success: function(data) {
$("#classname").html(data);
}
});
});
});
</script>
</head>
<body>
<h1>Get Notes:</h1>
<br/>
<form action="dropdown2.php" method="post">
State: <select id="state" name="state">
<option>--Select State--</option>
<?php
$sql = "SELECT states FROM states";
$result = mysql_query($sql);
while ($output = mysql_fetch_array($result)) {
$state_name = $output['states'];
echo "<option value=\"$state_name\">$state_name</option>";
}
?>
</select>
<br/>
School: <select id="school" name="school">
<option>--Select School--</option>
</select>
<br/>
Class Name: <select id="classname" name="classname">
<option>--Select Class Name--</option>
</select>
<br/>
Class Number: <select id="classnumber" name="classnumber">
<option>Select Class Name</option>
</select>
<br/>
<input type="submit" value="Search" />
</form>
</body>
</html>
Dropdown.php:
<?php
include_once("connect.php");
$state=$_POST["state"];
$result = mysql_query("select schools FROM schools where states='$state' ");
while($school = mysql_fetch_array($result)){
echo"<option value=".$school['schools'].">".$school['schools']."</option>";
}
?>
Dropdown2.php
<?php
include_once("connect.php");
$school=$_POST['school'];
$result = mysql_query("SELECT school_id FROM schools WHERE schools='$school' ");
$school_id = mysql_fetch_array($result);
$id = $school_id['school_id'];
$classname = mysql_query("SELECT DISTINCT class_abrv FROM classes WHERE school_id='$id' ORDER BY class_abrv asc");
while($class = mysql_fetch_array($classname)){
echo"<option value=".$class['class_abrv'].">".$class['class_abrv']."</option>";
}
?>
in second ajax function you have assigned the school drop down box value to state variable but you pass the variable school to ajax post. So there is no school variable that is why you get error.
$("#school").change(function(){
var *state* = $("#school").val();
//above variable should be school.
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+*school*,
success: function(data) {
$("#classname").html(data);
}
});
});
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>";
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');
};