i need help for this problem.
I want to make a dynamically dropdown and when i select a value from one dropdown to "A", the another dropdown will be set to "B".
I have a javascript function for dynamically dropdown like this.
<script type="text/javascript">
function coba(){
document.getElementById("add").innerHTML +=
" <inputclass='department_name' type='text'
size='50' />";
}
</script>
REFERENCE: how to dynamically change item of two related combobox
In Short:
In file1.php, Retrieve mysql tbl1 and display it in a combo box A.
On change of Combo box A, Fetch the value of option and pass it a php file file2.php via ajax and Display the output in file1.php which is produced by file2.php.
In file2.php, Retrieve mysql tbl2 with the Id passed by Ajax and generate a combo box B.
Example:
index.php
<script type="text/javascript">
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function ajax_function(url, postData, id)
{
xmlhttp=GetXmlHttpObject();
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", postData.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send(postData);
}
function dispSecond(Id)
{
var params = 'Id=' + Id ;
var DivId = 'dispDiv';
ajax_function('ajax_display.php', params, DivId);
}
</script>
<?php
/* Mysqli query to retrieve and store in $ArrayList(Id=>Text)
Example: $ArrayList = array(1=>'Ford',2=>'Chevy');
*/
?>
<select id="drop_first" name="drop_first" onchange="return dispSecond(this.value);">
<option value="0">[Select]</option>
<?php
foreach ($ArrayList as $k=>$v)
{
echo '<option value="'.$k.'">'.$v.'</option>';
}
?>
</select>
<div id="dispDiv"></div>
ajax_display.php
<?php
$Id = isset($_REQUEST['Id']) ? $_REQUEST['Id'] : '';
if ($Id)
{
/* Mysqli query to retrieve and store in $SubArray where $Id
Example:
If $Id=1
$SubArray = array(1=>'Focus',2=>'Explorer');
If $Id=2
$SubArray = array(1=>'Cavalier',2=>'Impala', 3=>'Malibu');
*/
?>
<select id="drop_second" name="drop_second">
<option value="0">[Select]</option>
<?php
foreach ($SubArray as $k=>$v)
{
echo '<option value="'.$k.'">'.$v.'</option>';
}
?>
</select>
<?php
}
?>
Note:
Use Mysqli or PDO instead mysql
Below Demo and Download are based on arrays, you can implement by using mysqli retrieval.
Also You can try using $.ajax which is more easy also.
DEMO | DOWNLOAD
Related
i have two dropdown list box,first one is sales area contain different kind of alphabet which get from cookie,second dropdown staff name is to change according to the selected value from first dropdown. How can i manage to pass the selected option value to my sql query so that it can be change according to the selected sales area.
This is the results that i want to get I insert my code to the snippet for easy to do edit and demonstration.
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'updateleave.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("slct2").innerHTML=response;
}
});
<table >
<tr>
<td> Sales Area
<select name="Area" id="area" >
<?php
$sarea = explode(",",$_COOKIE['cooAreaCode']);
foreach($sarea as $item){
?>
<option value="<?php echo strtolower($item); ?>"><?php echo $item; ?></option>
<?php
}
?>
</select >
</td>
<?
$var = $_POST['Area'];
$sql = "SELECT StaffName FROM tblStaff WHERE AreaCode= '$var'";
$rs = odbc_exec($link,$sql);
while ($row = odbc_fetch_array($rs)) {
$porr[] = $row;
}
odbc_free_result($rs);
odbc_close($link);
?>
<td> Staff Name
<select id="slct2">
?>
</select>
</td>
<label class="form_field">Your selected <span id="aggregator_name"></span></label>
(updateleave.php)
if (isset($_POST['get_option'])) {
$item=$_POST['get_option'];
$sql = "SELECT StaffName FROM tblStaff WHERE AreaCode= '$item'";
$rs = odbc_exec($link,$sql);
while ($row = odbc_fetch_array($rs)) {
$porr[] = $row;
}
for($i=0; $i < count($porr);$i++) {
echo "<option value="strtolower($porr[$i]['StaffName']);" >" .$porr[$i]['StaffName']."</option>";
odbc_free_result($rs);
odbc_close($link);
}
?>
Use append to add option tags with in select tag also do all the work in change event of the first drop down ("#area")
$(document).ready(function(){
$("#area").change(function()
{
var val =$(this).val();
$.ajax({
type: 'post',
url: 'updateleave.php',
data: {
get_option:val
},
success: function (response) {
$("#clct2").append(response);
}
});
});
});
I'm not a fan of jQuery, so you'll need to convert my Javascript to your needs, but what you need is to capture an onchange event for the first drop down and use it to dynamically process the SQL for the second dropdown.
<script>
document.getElementById('area').onclick = function(){
var xmlhttp;
var formData = new FormData();
formData.append('area_value', this.value);
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText); // for DEBUGGING.
if(xmlhttp.responseText == 'false'){
alert(xmlhttp.responseText);
} else {
document.getElementById('slct2').innerHTML = xmlhttp.responseText;
}
}
}
xmlhttp.open("POST", 'build_slct2.php');
xmlhttp.send(formData);
xmlhttp.onerror = function () { console.error(xmlhttp.statusText); }
}
</script>
The build_slct2.php script would use $_POST['area_value'] to create the desired SQL query, process the query, and build the <option></option> list that will end up in the slct2 drop down. The build_slct2.php file would simply echo the new contents for slct2.
I have two mySQL tables tbl1 and tbl2 tbl1 has a primary key column who reference in tbl2 column. Now I have html form in which two combobox is available . I shows all data of tbl1 into first combobox. Now I want to show the related data of tbl2 into second combobox after selection of item in first combobox.
So please explain me simple and easy technique to achieve it. Thanks in advance.
In Short:
In file1.php, Retrieve mysql tbl1 and display it in a combo box.
On change of Combo box, Fetch the value of option and pass it a php file file2.php via ajax and Display the output in file1.php which is produced by file2.php.
In file2.php, Retrieve mysql tbl2 with the Id passed by Ajax and generate a combo box.
Example:
index.php
<script type="text/javascript">
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function ajax_function(url, postData, id)
{
xmlhttp=GetXmlHttpObject();
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", postData.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send(postData);
}
function dispSecond(Id)
{
var params = 'Id=' + Id ;
var DivId = 'dispDiv';
ajax_function('ajax_display.php', params, DivId);
}
</script>
<?php
/* Mysqli query to retrieve and store in $ArrayList(Id=>Text)
Example: $ArrayList = array(1=>'Ford',2=>'Chevy');
*/
?>
<select id="drop_first" name="drop_first" onchange="return dispSecond(this.value);">
<option value="0">[Select]</option>
<?php
foreach ($ArrayList as $k=>$v)
{
echo '<option value="'.$k.'">'.$v.'</option>';
}
?>
</select>
<div id="dispDiv"></div>
ajax_display.php
<?php
$Id = isset($_REQUEST['Id']) ? $_REQUEST['Id'] : '';
if ($Id)
{
/* Mysqli query to retrieve and store in $SubArray where $Id
Example:
If $Id=1
$SubArray = array(1=>'Focus',2=>'Explorer');
If $Id=2
$SubArray = array(1=>'Cavalier',2=>'Impala', 3=>'Malibu');
*/
?>
<select id="drop_second" name="drop_second">
<option value="0">[Select]</option>
<?php
foreach ($SubArray as $k=>$v)
{
echo '<option value="'.$k.'">'.$v.'</option>';
}
?>
</select>
<?php
}
?>
Note:
Use Mysqli or PDO instead mysql
Below Demo and Download are based on arrays, you can implement by using mysqli retrieval.
Also You can try using $.ajax which is more easy also.
DEMO | DOWNLOAD
TABLE wp_thesis TABLE wp_courses
Thesis_ID Thesis_Title Course_ID Thesis_ID Course
1 thesis1 1 1 course1
2 thesis2 2 1 course2
3 2 course1
4 2 course2
5 2 course3
I have a select that calls the showText function onchange.
$query = "SELECT * FROM wp_thesis";
$result = mysqli_query($conn,$query);?>
<select name="ThesisTitle" onchange="showText(x,y)" required="">
<option disabled='disabled' selected='selected' value=''></option>"; <?php
foreach ($result as $row)
{
echo "<option value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";?>
First thought was to send the value of the select (onchange="showText(this.value)") and then have an sql query inside showText function in order to get the two values i wanted. I read that you can't execute sql queries inside functions because Javascript is client-side, so I thought to do the sql query on php and then send the values to showText function. The query I want is this:
$query = "SELECT Course FROM wp_courses WHERE Thesis_ID={$row[Thesis_ID]} ";
$courses = mysqli_query($conn,$query);
$coursesNo = mysqli_num_rows($courses);
Tha values I want to send are $courses and $coursesNo. Is it possiple to get the value of select in the same php file, without using a button or anything like that?
Get X and Y co-ordinate before rendering option and provide it as data attribute.
<select name="ThesisTitle" onchange="showText(this)" required="">
<option disabled='disabled' selected='selected' value=''></option>"; <?php
foreach ($result as $row)
{
echo "<option data-x={$row[Thesis_X]} data-y={$row[Thesis_Y]} value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";?>
Just after that go to showText(this) function with this as parameter and get the attribute with
function showText(obj){
var x_val = $(obj).attr("data-x");
var y_val = $(obj).attr("data-y");
}
Hope this helps to you.
I finally found what I needed. I am posting the code.
<script language="javascript" type="text/javascript">
//Browser Support Code
function showCourses(str){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Problem with your browser!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('courses'); // where it should be displayed
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value and pass it to server script.
var queryString = "?thesis_id=" + str ;
ajaxRequest.open("GET", "http://localhost/wordpress/get_thesis/" + queryString, true);
ajaxRequest.send(null);
}
From the select:
<select name="ThesisTitle" id="link_block" onchange="showCourses(this.value)" required="">
<option disabled='disabled' selected='selected' value=''></option>";<?php
foreach ($result as $row)
{
echo "<option value= {$row[Thesis_ID]}>{$row[Thesis_Title]}</option>";
}
echo"</select><br />";?>
I am sending the Thesis_ID to http://localhost/wordpress/get_thesis/ which is a php file that does the query I needed.
I have a bootstrap select menu which I want to populate onChange from another select menu. I think I have some problems with returning the data from PHP.
Select menu:
<div class="col-md-6" style="width:100%;margin-bottom: 10px;">
<div class="input-group" style="width:100%;">
<span style="width:50%;" class="input-group-addon" id="basic-addon1">Municipality *</span>
<select class="selectpicker" name="object_Municipality" id="object_Municipality">
<option value="0" selected="selected" >Municipality *</option>
</select>
</div>
</div>
Javascript function (called onChange from another select menu) to populate the select menu:
function populate_obcina(value) {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("object_Municipality").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_Municipality.php?q="+value,true);
xmlhttp.send();
}
My get_Municipality.php file:
<?php
require_once 'functions.php';
$conn = dbConnect();
$q =($_GET['q']);
$municipality = mysqli_query($conn, "SELECT id,municipality FROM municipalities WHERE `region`='".$q."'") or die(file_put_contents('error_querry.txt', print_r("Error: " . mysqli_error($conn), true)));
while ($row = mysqli_fetch_array($municipality, MYSQLI_ASSOC)) {
$fp = fopen("while_loop.txt", "a") or die("Couldn't open log file for writing.");
fwrite($fp, PHP_EOL .'<option value="'.$row['id'].'">'.$row['municipality'].'</option>');
fflush($fp);
fclose($fp);
//In the while_loop.txt I get lines like this:
//<option value="1">Chicago</option>
//so I guess the problem is the way I am returning the results
echo '<option value="'.$row['id'].'">'.$row['municipality'].'</option>';
}
mysqli_close($conn);
?>
This is the return I get:
<option value="1">Chicago</option><option value="2">LA</option><option value="3">California</option>
I already did that kind of job, but I did it differently since I had to be able to populate many kinds of selects, on events, with pre-chosen data or not, ... with Jquery, bootstrap, & so on...
SELECT HTML :
<div class="col-md-6" style="width:100%;margin-bottom: 10px;">
<div class="input-group" style="width:100%;">
<span style="width:50%;" class="input-group-addon" id="basic-addon1">Municipality *</span>
<select class="selectpicker" name="object_Municipality" id="object_Municipality">
<option value="0" selected="selected" >Municipality *</option>
</select>
</div>
</div>
Javascript/Jquery populate "class", just make a file called PopulateList.js like this :
function PopulateList(){ }
PopulateList.municipality = function(element,choice){
$(document).ready(function(){
$.ajax({
type : 'POST',
url : './getMunicipalitiesChoice.php',
data : {'choice':choice},
dataType : 'json',
error : function(response){
alert('SOMETHING WENT WRONG');
},
success : function(response){
element.html(response);
}
});
});
};
JQuery On change event :
$(document).on('change','#listFiringTheEvent',function(){
//Call the populate function here
populateList.municipality('#object_Municipality',$(this).val());
});
PHP getMunicipalitiesChoice.php :
<?php
require_once 'functions.php';
if(isset($_POST['choice'])){
$conn = dbConnect();
$q = $_POST['choice'];
$result = '';
$municipality = mysqli_query($conn, "SELECT id,municipality FROM municipalities WHERE `region`='".$q."'") or die(file_put_contents('error_querry.txt', print_r("Error: " . mysqli_error($conn), true)));
while ($row = mysqli_fetch_array($municipality, MYSQLI_ASSOC)) {
$fp = fopen("while_loop.txt", "a") or die("Couldn't open log file for writing.");
fwrite($fp, PHP_EOL .'<option value="'.$row['id'].'">'.$row['municipality'].'</option>');
fflush($fp);
fclose($fp);
$result.='<option value="'.$row['id'].'">'.$row['municipality'].'</option>';
}
mysqli_close($conn);
echo json_encode($result);
}else{
//If you're here, that's because the file has been called with a "invalid" choice (not set)
}
?>
Now, as you said, if you have some other lists to fill, just add functions in your PopulateList.js file like this, for example, a function that fills a list with ALL municipalities, not depending on any choice :
PopulateList.municipalities = function(element){
$(document).ready(function(){
$.ajax({
type : 'POST',
url : './getMunicipalities.php',
dataType : 'json',
error : function(response){},
success : function(response){
element.html(response);
}
});
});
};
OR for example you fill a "cities" list when you chose a "municipality" :
PopulateList.citiesOnMunicipality= function(element,municipality){
$(document).ready(function(){
$.ajax({
type : 'POST',
url : './getCitiesOnMunicipality.php',
data : {'municipality':municipality},
dataType : 'json',
error : function(response){},
success : function(response){
element.html(response);
}
});
});
};
In my example here, I assume that your html and php code are "good".
But (for PHP) you have to use prepared statements...
Hope this helps!
I am not able to retrieve multiple select data from database without loading page.
I want to select more than one option and retrieve data depending on selection, here is the code for my select tag:
<select name="country[]" multiple="multiple" onChange="getSkill(this.value)">
<option value="">--Select Categoery--</option>
<?php while ($row=mysql_fetch_array($result)) {
$cid = $row['cid'];
?>
<option value=<?php echo $row['cid']?>><?php echo $row['categotie']?></option>
<?php } ?>
</select>
And my AJAX code is:
function getSkill(cid) {
var strURL="findskill.php?cid="+cid;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('skilldiv').innerHTML=req.responseText;
} else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
document.getElementById('marksdiv').innerHTML='<p name="marks">'+
'</p>';
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
How can I retrieve multiple values?, I am able to retrieve only one value.
Depending on what you expect in your server have to correctly get the value, when working with multiple selections, instead of:
<select name="country[]" multiple="multiple" onChange="getSkill(this.value)">
If you are using jQuery, replace with:
<select name="country[]" multiple="multiple" onChange="getSkill($(this).val())">
Note that if you don't use jQuery you need a longer code.
Then, your function will receive [cid1, cid2, cid3, ....].
Then, it depends on your server code, for example, if you expect in your server cid1,cid2,cid3, replace:
var strURL="findskill.php?cid="+cid;
with:
var strURL = "findskill.php?cid=" + cid.join(',');
Fiddle