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.
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
})
})
what i want to do:
1.) is shown on page after first load.
When an user selects one or multiple options dynamic content is loaded into a <div>
2.) in this first dynamic <div> an other php page echos a second with further entries.
--- till here my code works just fine ---
3.) after selecting one or multiple options in this second <select> in the first dynamic <div> a second dynamic <div> should be printed with another <select>
But after selecting entries from second nothing is shown in second dynamic
Example:
- Page Load: First Cars, Bikes, Trucks, Planes...
- I choose "Cars"
- First dynamic <div> shows: <select> Mustang, Chrysler, Jeep, etc...
- I choose Chrysler
(till here my code works fine)
- Second dynamic <div> shows: red, white, brown, yellow, ...
My Code:
Page which is loaded in browser:
<!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>Unbenanntes Dokument</title>
</head>
<body>
<?
include_once('includes/functions.inc.php');
$conn = connection();
$sql = "SELECT * FROM Faecher WHERE Fach_Studienabschnitt = 1 ORDER BY Fachname ASC";
$sql_erg_VKH_Faecher = send_sql($sql);
mysql_close($conn);
?>
<!-- the select -->
<select name="Fach[]" size="25" multiple="multiple" id="Fach">
<?
echo '<optgroup label="Vorklinik-Humanmedizin">';
while($vkhfaecher = mysql_fetch_array($sql_erg_VKH_Faecher)){
echo "<option value=".$vkhfaecher['Fach_ID'].">".$vkhfaecher['Fachname']."(".$faecher[$vkhfaecher['Fach_ID']]['Fragenanzahl'].")"."</option>";
}
echo '</optgroup>';
?>
</select>
<!-- the DIVs -->
<div id="Semester"></div>
<div id="Tags"></div>
<!-- the jQuery -->
<script type="text/javascript" src="scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$('#Fach').change(function(event) {
var form_data = $('#Fach').serialize();
$.ajax({
url: "ajax_reload.php",
type: "post",
data: form_data,
success: function(data){
//adds the echoed response to our container
$("#Semester").html(data);
}
});
});
</script>
<script type="text/javascript">
$('#Semester').change(function(event) {
var form_data = $('#Semester').serialize();
$.ajax({
url: "ajax_reload.php",
type: "post",
data: form_data,
success: function(data){
//adds the echoed response to our container
$("#Tags").html(data);
}
});
});
</script>
</body>
</html>
ajax_reload.php which dynamically loads content from mysql_db:
<?
session_start();
include_once('includes/functions.inc.php');
$conn = connection();
if(isset($_POST['Fach'])){
foreach($_POST['Fach'] as $elem){
$sql_fach_temp1 .= "T1.Fach_ID = ".$elem." OR ";
$sql_fach_temp2 .= "T2.Fach_ID = ".$elem." OR ";
}
$sql_fach_temp1 = substr($sql_fach_temp1, 0, -4);
$sql_fach_temp2 = substr($sql_fach_temp2, 0, -4);
$_SESSION['ajax_sql'] = "(".$sql_fach_temp1.") AND (".$sql_fach_temp2.")";
$sql = "SELECT DISTINCT T3.Semester,T3.Semester_ID FROM Fragen T1, Faecher T2, Semester T3 WHERE (".$sql_fach_temp1.") AND (".$sql_fach_temp2.") AND T1.Semester_ID = T3.Semester_ID";
$FaecherSemester_temp = send_sql($sql);
echo '<select name="Semester[]" size="25" multiple="multiple" id="Semester">';
while($semesterliste = mysql_fetch_array($FaecherSemester_temp)){
echo "<option value=".$semesterliste['Semester_ID'].">".$semesterliste['Semester']."</option>";
}
echo "</select>";
}
if(isset($_POST['Semester'])){
echo $_SESSION['ajax_sql']."ja";
foreach($_POST['Semester'] as $elem){
$sql_semester_temp .= "T3.Semester_ID = ".$elem." OR ";
}
$sql_semester_temp = substr($sql_semester_temp, 0, -4);
$sql = "SELECT DISTINCT T4.Tag, T4.Tag_ID FROM Fragen T1, Faecher T2, Semester T3, Tags T4, Frage_Tags T5 WHERE ".$_SESSION['ajax_sql']." AND (".$sql_semester_temp.") AND T1.Semester_ID = T3.Semester_ID AND T4.Tag_ID = T5.Tag_ID AND T1.Frage_ID = T5.Frage_ID";
$FaecherSemesterTags_temp = send_sql($sql);
echo '<select name="Tags[]" size="25" multiple="multiple" id="Tags">';
while($tagsliste = mysql_fetch_array($FaecherSemesterTags_temp)){
echo "<option value=".$tagsliste['Tags_ID'].">".$tagsliste['Tags']."</option>";
}
echo "</select>";
}
mysql_close($conn);
?>
I tried to copy the ajax code into ajax_reload.php so that the cod is echoed into the dynamic <div>, but no response...
any idea?
thanks a lot!
Since the #Semester SELECT is added dynamically, you need to use event delegation:
$('#SemesterDiv').on("change", "#Semester", function(event) {
var form_data = $('#Semester').serialize();
$.ajax({
url: "ajax_reload.php",
type: "post",
data: form_data,
success: function(data){
//adds the echoed response to our container
$("#TagsDiv").html(data);
}
});
});
I'm assuming you renamed <div id="Semester"> to <div id="SemesterDiv">, and similarly for the Tags DIV.
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 am creating a MySQL query that will be execute when user select options from more a dropdown lists.
What I want is, on selecting a dropdown list option a query related to that option should be automatically executed using ajax/javascript on the same page. As I have the both html and php code on the same page.
Earlier I was using form submit options for dropdown list but as the number of dropdown option are more than five for filtering the result so queries became complicated to implement. That's why I want to refine result of each dropdown individually.
Any help is appreciated. Thanks in advance!
My HTML code for dropdown list is:
<p>
<label for="experience">Experience :</label>
<select id="experience" name="experience">
<option value="" selected="selected">All</option>
<option value="Fresher">Fresher</option>
<option value="Experienced">Experienced</option>
</select>
</p>
PHP code for executing related queries is:
<?php
if (isset($_GET['exp'])) {
switch ($_GET['exp']) {
case 'Experienced':
$query = "SELECT job_seekers.ID, job_seekers.Name, job_seekers.Skills, job_seekers.Experience FROM job_seekers where job_seekers.Experience!='Fresher'";
break;
case 'Fresher':
$query = "SELECT job_seekers.ID, job_seekers.Name, job_seekers.Skills, job_seekers.Experience FROM job_seekers where job_seekers.Experience='Fresher'";
break;
default:
$query = "SELECT job_seekers.ID, job_seekers.Name, job_seekers.Skills, job_seekers.Experience FROM job_seekers";
}
}
$result = mysql_query($query) or die(mysql_error());
echo "<ul class=\"candidates\">";
while($row = mysql_fetch_row($result))
{
echo "<li>";
echo "<p> <b>ID:</b> <u>$row[0]</u> </p>";
echo "<p> <b>Name :</b> $row[1] </p>";
echo "<p> <b>Key Skills:</b> $row[2] </p>";
echo "<p> <b>Experience:</b> $row[3] </p>";
echo "</li>";
}
echo "</ul>";
?>
When you want to AJAX call a php script, you should you $.ajax provided by Jquery
http://api.jquery.com
so you can use it like so:
$.ajax({
url: 'ajax.php',
data: {
//put parameters here such as which dropdown you are using
},
success: function(response) {
//javascript and jquery code to edit your lists goes in here.
//use response to refer to what was echoed in your php script
}
});
this way, you will have dynamic dropdowns and the refined results you want
<?php
if (isset($_GET['experience'])) {
echo $_GET['experience'];
/* do mysql operations and echo the result here */
exit;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
function myFunction(value)
{
if(value!="All")
{
$.ajax(
{
type: "GET",
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { experience: value},
success: function(data) {
$('#resultDiv').html(data);
}
});
}
else
{
$('#resultDiv').html("Please select a value.");
}
}
</script>
</head>
<body>
<p>
<label for="experience">Experience :</label>
<select id="experience" name="experience" onChange="myFunction(this.value)">
<option value="All" selected="selected">All</option>
<option value="Fresher">Fresher</option>
<option value="Experienced">Experienced</option>
</select>
</p>
<div id="resultDiv">
Please select a value.
</div>
</body>
</html>
You cannot re-execute a PHP part on the same page. Rather use Ajax request to perform the action.
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');
};