Passing 2 value from 2 dropdown into 3rd dropdown - php

I have tried passing value on 3rd drop down but it doenst receive any of it
it doesnt show error but it doesnt get any data from 2 dropdowns Im new to just and im trying something but it doesnt work at all pls help thank you very much
dropdown.php
<select class="form-control" style="font-size: 21px;" name="Building" id="Building" onChange="change_floor(this.value)">
<option>Select</option>
<?php
$res=mysqli_query($conn,"select * from Building");
while($row=mysqli_fetch_array($res)){
?>
<option value="<?php echo $row['Building']; ?>"><?php echo $row['Building'];?></option>
<?php
}
?>
</select>
<select class="form-control" style="font-size: 21px;" name="floor" id="Floor" onChange="change_floor(this.value)">
<option>Select</option>
<?php
$res=mysqli_query($conn,"select * from floor");
while($row=mysqli_fetch_array($res)){
?>
<option value="<?php echo $row['Floor']; ?>"><?php echo $row['Floor'];?></option>
<?php
}
?>
</select>
<div id="Dept"></div>
</div>
</div>
<script type="text/javascript ">
function change_floor(str,str1) {
if (str.length == 0) {
document.getElementById("Dept").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("Dept").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "deptajax.php?q="+str+"&d="+str1, true);
xmlhttp.send();
}
}
</script>
deptajax.php
If I use request here i shows error but if I use GET i doesnt show any error what is more usable for this scenario?
<?php
$link=mysqli_connect("localhost","id5592115_retep","Password");
mysqli_select_db($link,"id5592115_admin");
$q = $_REQUEST["q"];
$d = $_REQUEST["d"];
$res=mysqli_query($link,"select * from depttable where Flr='$d' and
Building='$q' order by deptname asc");
echo "<form method='get' action='table2.php'>";
echo '
<select class="form-control" style="font-size: 21px;" name="dept">
';
while ($row=mysqli_fetch_array($res)) {
$deptid = $row['deptid'];
$deptname = $row['deptname'];
echo "<option value='".$deptname."'>".$deptname."</option>";
}
echo "</select>";
echo '<button type="submit" class="btn btn-light
btnmove">Submit</button>';
echo "</form>";
?>

Your onclick function is call every time you select any of the dropdown , so at a time only one value is passed i.e : either str or str1 will have value . Instead to avoid this you can do like below :
When first selectbox is selected try to store it value in some variable like below :
<select class="form-control" style="font-size: 21px;" name="floor" id="Floor"
onChange="change_floor1(this.value)">
<!--^ make another function with name change_floor1-->
<option>Select</option>
...
</select>
Then in your <script></script>do like below :
var s; // declare globally
function change_floor1(str) {
s=str; //assigning value of first-select box in "s"
}
function change_floor(str1) {
if (str1.length == 0) {
document.getElementById("Dept").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("Dept").innerHTML = this.responseText;
}
};
//passing both value
xmlhttp.open("GET", "deptajax.php?q="+s+"&d="+str1, true);
xmlhttp.send();
}
}

Related

Populate datalist with mysql fields based on input from another field without reloading page

I am trying to set up a datalist tag that uses fields from my database based on the input from the first field on the form.
I am trying to use AJAX to send the value in the first field (Builder) into my PHP file which will run a query to pull all the records based on that value. Then it echos the options into the datalist for all the contactnames available under that Builder.
<form id="newsurveyform" method="post" action="submitnewsurvey.php">
ID: <input type="text" name="ID" readonly value=<?php print $auto_id; ?>>
Builder:<b style="color:red">*</b> <input list="builders" name="builders" onchange="findcontactnames(this.value)" required>
<datalist id="builders">
<?php
while ($builderinforow = mysqli_fetch_assoc($builderinfo)){
echo'<option value="'.$builderinforow['Builder'].'">';
}
?>
</datalist>
Contact Name:
<input list="contactnames" name="contactnames" required>
<datalist id="contactnames">
<div id="contactnamesoptions"> </div>
</datalist>
</form>
<!-- AJAX, send builder value to php file-->
<script>
function findcontactnames(str) {
if (str.length==0){
document.getElementById("contactnames").innerHTML = "";
return;}
else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("contactnamesoptions").innerHTML = this.responseText;
}};
xmlhttp.open("POST", "contactnames.php", true)
xmlhttp.send(str);
}
}
</script>
<?php
include 'dbconnector.php';
$buildername = $_POST["Builder"];
$contactnames = $conn->query("SELECT ContactName FROM SurveyLog'.$buildername.'");
while ($contactnamerow = mysqli_fetch_assoc($contactnames)){
echo'<option value="'.$contactnamerow['ContactName'].'">';
}
?>
Once the user enters the builder, they will click the contact name and it should be populated with all the contact names under that builder.
Right now, it is not populating anything into the contact name field.
In index.php
<form id="newsurveyform" method="post" action="submitnewsurvey.php">
ID: <input type="text" name="ID" readonly value=<?php print $auto_id ?? 0; ?>>
Builder:<b style="color:red">*</b> <input list="builders" name="builders" onchange="findcontactnames(this.value)" required>
<datalist id="builders">
<?php
while ($builderinforow = mysqli_fetch_assoc($builderinfo)){
echo'<option value="'.$builderinforow['Builder'].'">';
}
?>
</datalist>
Contact Name:
<input list="contactnames" name="contactnames" required>
<datalist id="contactnames">
<div id="contactnamesoptions"> </div>
</datalist>
</form>
<!-- AJAX, send builder value to php file-->
<script>
function findcontactnames(str) {
if (str.length==0){
document.getElementById("contactnames").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(this);
if (this.readyState == 4 && this.status == 200) {
alert('Fired');
document.getElementById("contactnamesoptions").innerHTML = this.responseText;
// document.getElementById("contactnamesoptions").innerHTML = "working";
}
};
xmlhttp.open("POST", "response.php", true)
xmlhttp.send(str);
}
}
</script>
in response.php
<?php echo "test"; ?>
Once you've verified that works, query the database
EDIT:
Now that you've verified that, query the database in response.php
include 'dbconnector.php';
$buildername = $_POST["Builder"];
$contactnames = $conn->query("SELECT ContactName FROM SurveyLog WHERE `columnName` LIKE '.$buildername.' LIMIT 100");
$queryHTML = '';
$result = 0;
while ($contactnamerow = mysqli_fetch_assoc($contactnames)){
$result = 1;
$queryHTML .= '<option value="'.$contactnamerow['ContactName'].'">';
}
if ($result == 1) {
echo $queryHTML;
} else {
echo 'No Builders found';
}
Note: Change the columnName in the query to your real column name

Function not renaming field pulled from another page

I have a form which is cloned when needed, inside this form I have a div, this div is replaced by a div pulled from another page which has new select options based on a select option from a above field.
Each 'cloned' forms fields are given a new name with a function, but this function seems to have trouble seeing the field that is pulled in as part of the form and isn't generating a new name for it.
Could Someone kind enough show me the way please?
function;
$(document).ready(function() {
var newNum = 2;
cloneMe = function(el) {
var newElem = el.clone().attr('id', 'container' + newNum);
newElem.html(newElem.html().replace(/form\[1\]/g, 'form['+newNum+']'));
newElem.html(newElem.html().replace(/id="(.*?)"/g, 'id="1'+newNum+'"'));
$('#cloneb').before(newElem);
$('#delete_name'+ newNum).html('<p id="rem_field"><span>Delete Line</span></p>');
newNum++;
};
$('p#rem_field').live('click', function() {
$(this).parents('div').remove();
return false;
});
});
form;
<form action='' method='post' enctype='multipart/form-data' name='form' id='form'>
<div id="container1">
<div class="instance" id="instance">
<label>Style:</label>
<select name='form[1][style]' id='style' class='style' onchange="showDim(this)">
<option value='0' class='red'>Select a style...</option>
<?php
include ('connect.php');
$getsty = $db->prepare("SELECT Style_ID, Style_Type FROM style ORDER BY Style_Type ASC LIMIT 1, 18446744073709551615;");
$getsty->execute();
while($row = $getsty->fetch(PDO::FETCH_ASSOC)) {
$Style_ID = $row['Style_ID'];
$Style_Type = $row['Style_Type'];
echo " <option value='$Style_ID'>$Style_Type</option>";
}
?>
</select>
<br />
<div class='dimdiv'>
<label>Dimensions:</label>
<select name='form[1][Dim]' id='Dim'>
<option value='0' class='red'>Select the dimensions...</option>
</select>
</div>
<br />
<label>Colour:</label>
<select name='form[1][Colour]' id='Colour'>
<option value='0' class='red'>Select a colour...</option>
<option value='Colour1'>Colour #1</option>
<option value='Colour2'>Colour #2</option>
<option value='Colour3'>Colour #3</option>
<option value='Colour4'>Colour #4</option>
</select>
<br />
<label>Quantity:</label>
<input type='text' name='form[1][Quantity]' id='Quantity'>
<br />
</div>
<div id="delete_name" style="margin:15px 0px 0px 0px; width:120px; height:30px;"></div>
</div>
<input type="button" id="cloneb" value="Clone" onclick="cloneMe($('#container1'));" />
<input type='submit' name='submit' value='Submit' class='buttons'>
</form>
Field pulled from get_dim.php;
<label>Dimensions:</label>
<select name='form[1][Dim]' id='Dim'>
<option value='0' class="red">Select the dimensions...</option>
<?php
$id = intval($_GET['id']);
include ('connect.php');
$getcus = $db->prepare("SELECT Dim_ID, Dim FROM dimentions WHERE Style_ID=? ORDER BY Dim ASC ");
$getcus->execute(array($id));
while($row = $getcus->fetch(PDO::FETCH_ASSOC)) {
$Dim_ID = $row['Dim_ID'];
$Dim = $row['Dim'];
echo " <option value='$Dim_ID'>$Dim</option>";
}
?>
</select>
Function to replace the dimdiv with get_dim.php;
function showDim(elem)
{
var elems = document.getElementsByClassName('style'),
groupIndex = -1,
targetDimDiv,
i;
for( i = 0; i < elems.length; ++i ) {
if( elems[i] == elem ) {
groupIndex = i;
break;
}
}
if( groupIndex == -1 )
{
return;
}
targetDimDiv = document.getElementsByClassName('dimdiv')[groupIndex];
if (elem.value == "")
{
targetDimDiv.innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function( ) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
targetDimDiv.innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","get_dim.php?id="+elem.value,true);
xmlhttp.send();
}
Your problem is, that form[1][Dim] is hard coded into get_dim.php. When you clone a form, you change the name of every element, but this AJAX request would still return a form element with name form[1][Dim] there too.
You can fix this, by reading out the current form id and passing it to get_dim.php and making the name generation there dynamic.
The parts you have to change (roughly):
replace function:
form_id = groupIndex + 1; // if I get groupIndex right
xmlhttp.open("GET","get_dim.php?id="+elem.value+"&form_id="+form_id,true);
get_dim.php:
<select name='form[<?php echo intval($_GET['form_id']); ?>][Dim]' id='Dim'>

Dynamic drop down list not working

I am trying to pass a js var to a php var, then use that php var to go through and array and populate a drop down list. I can see that the php var is getting the right value but list2 and list3 are not being populated.
If I put the string in myself $list1 = 'somestring'; it works, but when I use $list1 = $_POST['choice']; it doesn't work.
<script>
$(document).ready(function(){
$("#list1").change(function(){
var selected = this.value;
$.post("my.php", { choice: selected }, function(data){
alert(data);
});
});
});
</script>
<?php
echo'
<form name="menu">
<div>
<select name="list1" size="1" onchange="setOptions(document.menu.list1.options
[document.menu.list1.selectedIndex].value,document.menu.list2,document.menu.list3);">
<option value=" " selected></option>
<option value="one">item1</option>
<option value="two">item2</option>
<option value="three">item3</option>
<option value="four">item4</option>
</select><br><br>
<select name="list2" size="1"onchange="setOptions(document.menu.list2.options
[document.menu.list2.selectedIndex].value,document.menu.list3,' ');">
<option value=" " selected>Select an option</option>
</select><br><br>
<select name="list3" size="1">
<option value=" " selected>Select an option</option>
</select><br>
</div>
</form>';
?>
Drop down list
<script>
function setOptions(chosen, selbox, selbox2)
{
selbox.options.length = 0;
if (chosen == " ")
{
selbox.options[selbox.options.length] = new Option('Select an option',' ');
selbox2.options[selbox2.options.length] = new Option("Select an option"," ");
setTimeout(setOptions(' ',document.menu.list3),5);
}
if (chosen == "one")
{
showList2(selbox);
}
if (chosen == "two")
{
showList2(selbox);
}
if (chosen == "three")
{
showList2(selbox);
}
if (chosen == "four")
{
showList2(selbox);
}
//some code snipped
}
function showList2(selbox)
{
<?php
$n = 0;
$list1 = $_POST['choice'];
foreach($list[$list1] as $key => $value)
{
$key_array[$n] = $key;
$Lname[$n] = $list[$list1][$key]['name'];
$n++;
}
$jsArray = json_encode($key_array);
echo "var jsKeys = ". $jsArray . ";";
$jsArray = json_encode($Lname);
echo "var jsNames = ". $jsArray . ";";
?>
for (var i=0;i<jsKeys.length;i++)
{
var result = selbox2.options[selbox2.options.length] = new Option(jsNames[i],jsKeys[i]);
if(i == jsKeys.length-1)
{
var result = setTimeout(setOptions(jsKeys[0],document.menu.list3,' '),5);
}
}
return(result);
}
</script>
The $_POST superglobal is only set when the js function fires, ie when you choose something from the dropdown list. Otherwise remains empty.
You can check what's in the $_POST array with print_r($_POST)
Normally, I use a utility method to retrieve data from arrays:
function arrGet($array, $key, $default = NULL)
{
return isset($array[$key]) ? $array[$key] : $default;
}
This returns the value for the key or the default. Usage like:
if(arrGet($_POST, 'choice')){
//do something
}
Hope this helps...
<script>
$(document).ready(function(){
$("#list1").change(function(){
var selected = this.value;
$.post("my.php", { choice: selected }, function(data){
alert(data);
});
});
});
</script>
that little # in $("#list1") means the id of the element should be matched.
<select name="list1" ..... change it to <select name="list1" id="list1".....>

Loading data from database with php and pure ajax in a textbox

i have one dropdown list which has data for "subjects" loaded from database. when i clicked on one subject what it should do is load related "subject_id" value inside textbox which is just below dropdown list option. i dont know how to bring value from getbook.php and show in book_ID input text.
show_bookid(str) {
var xmlhttp;
if (str.length == 0) {
document.getElementById("bookid").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
strong text
xmlhttp = new ActiveXOjbject("Microsoft.XMLHttpRequest");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("bookid").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getbook.php?q=" + str, true);
xmlhttp.send();
}
getbook.php
<?php
<?php
$b = $_GET['q'];
include('includes/security.php');
include('includes/dbconnect.php');
$database = new MySQLDatabase();
$sql = "select * from tbl_bkcat where book_id='" . $b . "'";
$result = mysql_query($sql);
?>
?>
below is the File where i need to bring value
<form name="bookadd" action="" class="jNice" method="post">
<p>
<label>Subject</label>
<select name="subject" onChange="show_bookid(this.value);">
<?php while($sel_rows=mysql_fetch_array($subresult)) { ?>
<option value="<?php echo $sel_rows['book_id'];?>">
<?php echo $sel_rows[ 'subject']?>
</option>
<?php } ?>
</select>
</p>
<p>
<label>Book_Id</label>
<input type="text" id="bookid" class="text-small" />//where i need to load subject id</p>
The mistake was done at ajax part document.getElementById("bookid").innerHTML and must be replaced with document.getElementById().value since I had to put data to Html Element that cotain value i.e Textbox(as textbox contain value attribute).
InnerHTML is used to manipulate the html elements that does not contain value,
** div,h1, ** etc. for details see below link.
http://www.verious.com/qa/what-39-s-the-difference-between-document-get-element-by-id-quot-test-quot-value-and-document-get-element-by-id-quot-tes/
ajax code
function show_bookid(str)
{
var xmlhttp;
if(str.length==0)
{
document.getElementById("bookid").value="";
return;
}
if(window.XMLHttpRequest)
{
xmlhttp= new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXOjbject("Microsoft.XMLHttpRequest");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("bookid").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getbook.php?q="+str,true);
xmlhttp.send();
}
getbook.php
<?php
$b=$_GET['q'];
include('includes/security.php');
include('includes/dbconnect.php');
$database=new MySQLDatabase();
$sql="select * from tbl_bkcat where book_id='".$b."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
echo $row['Book_id'];
?>
addbook.php
<form name="bookadd" action="" class="jNice" method="post">
<fieldset>
<p><label>Subject</label>
<select name="subject" onChange="show_bookid(this.value);">
<?php
while($sel_rows=mysql_fetch_array($subresult))
{
?>
<option value="<?php echo $sel_rows['book_id'];?>">
<?php echo $sel_rows['subject']?>
</option>
<?php
}
?>
</select>
</p>
<p>
<label >Book ID</label>
<input type="text" id="bookid" name="book"/>
</p>
Your subject_id is not displaying because you have not printed your book_id after fetching results from database in getbook.php
After this $result=mysql_query($sql);
Write echo $result['your_book_id_field_name'];

How to populate one drop down with another using ajx, php and html

i want to populate a dropdownlist based on an input from another using ajax. But have head a deadend and can't figure out the problem. It uses company names to open up a dropdown list of mobile phone made by that company.
This is the source php file:
<body>
<div class="ex">
<form id="mob1" >
<label></br> Select Mobile 1:</label>
<label></br> --Company-- <label>
<select id="d1mob1" onchange="getmob(this.value)">
<?php
$q1=mysqli_query($con,"select distinct compName from umobile order by compName ASC");
while($row = mysqli_fetch_array($q1))
{
$options .="<option value=\"". $row['compName'] ."\">" . $row['compName'] . "</option>";
}
echo $options;
?>
</select>
<label class="ey" name="mlabel"></br> --Mobile--<label>
<select id="d2mob1" >
<?php
if($q2=mysqli_prepare($con,"SELECT DISTINCT mobname FROM umobile WHERE compName=? "))
{
mysqli_stmt_bind_param($q2,"s",$comp);
mysqli_stmt_execute($q2);
mysqli_stmt_bind_result($q2,$r);
}
while(mysqli_stmt_fetch($q2))
{
$name .="<option value=\"".$r."\" >".$r."</option>";
}
echo $name;
?>
</select>
</form>
</div>
</body>
This is the getmob php file being referred to inorder to query the mobile name :
<?php
$name="";
$comp=$_GET['d1mob1'];
if($q2=mysqli_prepare($con,"SELECT DISTINCT mobname FROM umobile WHERE compName=? "))
{
mysqli_stmt_bind_param($q2,"s",$comp);
mysqli_stmt_execute($q2);
mysqli_stmt_bind_result($q2,$r);
}
while(mysqli_stmt_fetch($q2))
{
$name .="<option value=\"".$r."\" >".$r."</option>";
}
echo $name;
?>
and finally this is javascript being used in the dropdownlist:
function getmob(compname)
{
var strURL="getmob.php?d1mob1="+compname;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) // only if "OK"
{
if (req.status == 200)
{
document.getElementById('mlabel').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
What am i missing ? Please help.
document.getElementById('mlabel')??? r you want to put the responseText in d2mob1?

Categories