I have a dynamic drop down box which calls another PHP page. I've got it to work just how I want it.
Below is the part of the form:
<tr>
<td>
<p> Select a delivery date </p>
</td>
<td>
<select name='listdate' onchange='showDelivery(this.value)'>
<option value=''>select delivery type:</option>
<option value='forwardorder'>Forward Order</option>
<option value='byreturn'>By Return</option>
</select>
<div id='txtHint'>
<b>Change to drop down box to display delivery date</b>
</div>
</td>
</tr>
The Ajax
function showDelivery(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getDelivery.php?q="+str,true);
xmlhttp.send();
}
The php script
$q=$_GET["q"];
// And create a cid object
require_once $CID_INCLUDE_PATH . "/cid.php";
$cid = new CHCID();
if ($q == 'forwardorder')
{
echo"<td><select 'name'='deliveryDate'/> ";
$listCapacityDates = $cid->ListCapacity();
foreach($listCapacityDates as $x) {
echo "<option value='".$x."'>".$x."</option> </select>";
}
}
if ($q == 'byreturn')
{
echo"<div id='div1'>Enter By Return Date<input type='text''name='deliveryDate' />
</div>";
}
I know the problem, because the results from the Ajax drop downs are shown through the PHP pages when the form submits none of those values are submitted. But I'm not sure how I can even submit them? Any ideas?
echo"<td><select 'name'='deliveryDate'/> ";
should be :
echo "<td><select name='deliveryDate'/> ";
and
echo"<div id='div1'>Enter By Return Date<input type='text''name='deliveryDate' />
should be :
echo"<div id='div1'>Enter By Return Date<input type='text' name='deliveryDate' />
and:
if ($q == 'forwardorder')
{
echo"<td><select 'name'='deliveryDate'/> ";
$listCapacityDates = $cid->ListCapacity();
foreach($listCapacityDates as $x) {
echo "<option value='".$x."'>".$x."</option>";
}
echo "</select></td>";
}
</select> should be outside foreach
You seem to understand why it's not working, just not how to correct it, right?
When you return the data from your PHP page, it needs to be processed via the javascript.
Instead of returning,
echo "<option value='".$x."'>".$x."</option> </select>";
It should be possibly json.
{ val : key, val : key }
Then Javascript can insert it into the HTML DOM, then your form will recongnize the values when you submit the form.
As for the Javascript code, there are a few ways, jQuery has some plugins for handle it.
Otherwise I can dig around for some code, if someone doesn't beat me too it :)
Edit:
Off hand, I think this code should work.
It's untested, but hopefully will give more of an idea how to use it.
replace
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
with
var response = xmlhttp.responseText;
var select = document.getElementByName('listdate');
var option;
for(var i=0; i<response.length; i++)
{
option = document.createElement("OPTION");
option.text = response.key[i];
option.value = response.val[i];
select.options.add(option);
}
Related
i want to link one drop down box menu and as i select one menu then it should show a list according to the selected menu using php,i used if else but its not working
<?php>
if(value="tata")
{
<option value="vista">vista</option>
<option value="nano">nano</option>
<option value="aria">aria</option>
<option value="manza">manza</option>
}
elseif(value="fiat")
{
<option value="linea">linea</option>
<option value="punto">punto</option>
}
elseif(value="maruti")
{
<option value="swift">swift</option>
<option value="desire">desire</option>
<option value="omni">omni</option>
<option value="maruti 800">maruti 800</option>
}
elseif(value="hundai")
{
<option value="santro">santro</option>
<option value="verna">verna</option>
}
?>
If you want dynamic list using php you shoud use ajax.
Try this Example:
use this ajax script
$(document).ready(function() {
$('#dropdown').change( function() {
$('#myform').submit();
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {
$('#output').html(response);
}
});
return false;
});
});
<form id=myform method=POST action="process.php">
<select id="dropdown" name="dropdown">
<option value="tata">TATA</option>
<option value="fiat">FIAT</option>
<option value="maruti">MARUTI</option>
<option value="hundai">HUNDAI</option>
</select>
</form>
<div id="output"></div>
process.php
<?php
$value = $_POST['dropdown'];
$html = "<select name = 'cars' id='cars'>";
if ($value == 'tata') {
$html .= "<option value='vista'>vista</option><option value='nano'>nano</option><option value='aria'>aria</option><option value='manza'>manza</option>";
} elseif($value == 'fiat') {
$html .= "<option value='linea'>linea</option><option value='punto'>punto</option>";
} elseif($value == 'maruti') {
$html .= "<option value='swift'>swift</option><option value='desire'>desire</option><option value='omni'>omni</option><option value='maruti 800'>maruti 800</option>";
} elseif($value == 'hundai') {
$html .= "<option value='santro'>santro</option><option value='verna'>verna</option>";
}
$html .= "</select>";
echo $html;
exit;
PHP, being a server side language will require the page to be refreshed (the form posted) before the value of the first selected drop down is available.
To do this without a page refresh, you will need to do so on the client side, using JavaScript. If the list is generated via PHP then you should look into AJAX.
//make array like this on header.php
$list = array(
'tata' => array(
'vista', 'nano', 'aria'
),
'fiat' => array(
'linea', 'punto'
),
'maruti' => array(
'swift', 'desire'
)
};
// your car.php where you going to do you action..call header.php here
<select name="Manuf" id="Manuf" onchange="show_car(this.value)">
<option value="">/option>
<?php
foreach($list as $x => $x_value)
{
echo '<option value="'.$x.'" >'.$x.'</option>';
}
?>
</select>
<select name="car" id="car"></select>
// Ajax Function For display car
function show_car(manuf)
{
var xmlhttp;
if (manuf.length==0)
{
alert("Select manufacturer");
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("car").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php?manuf="+manuf,true);
xmlhttp.send();
}
// code on ajax.php ..call header.php here too
foreach($list as $x => $x_value)
{
if($x == $_GET['manuf'])
{
for($i=0; $i<sizeof($x_value);$i++)
{
echo '<option value="'.$x_value[$i].'" >'.$x_value[$i].'</option>';
}
}
}
I'm trying to display data from database(MySQL) based on the option fields selected. I have two fields as shown below :
Select a Health Block : .......(list)
Select the year : .......(list)
When I select health block and year, data from database should be displayed on the same page itself. I've tried the following code. Actually the code works if I've only one option ('year') to be selected. What I need is to pass both the values (Health block and Year) to the page (getblock2.php) where I've written the code to retrieve data from database. Can anybody please help me to figure out where the problem is?
Mainpage
<html>
<head>
<script type="text/javascript">
var str11;
var str22;
function showB(str2)
{
str22=str2;
}
function showBlock2(str)
{
showB();
str11=str;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getblock2.php?q="+str11+"&h="+str22,true);
xmlhttp.send();
}
</script>
</head>
<body>
Select a Health block
<select name="h" onChange="showB(this.value)">
<option value="1">H1</option>
<option value="2">H2</option>
</select>
<br/>
Select a year
<select name="yr" onChange="showBlock2(this.value)">
<option>2012</option>
<option>2013</option>
</select>
<div id="txtHint" style="width:570px; height:auto" >
</div>
</body>
</html>
getblock2.php
<?php
include("connect.php");
$q=$_GET["q"];
$h=$_GET['h'];
$q="select Total_Cases from epidemics where Year1=$q and Hid=$h";
$r=mysql_query($q);
$i=0;
while($row=mysql_fetch_row($r))
{
$i++;
echo $i." ".$row[0]."<br/>";
}
?>
Variable str22 is not being assigned when you call showBlock2() on changing year. So replace the line
showB();
with
showB(document.getElementsByName("h")[0].value);
This would work when you select health and then year, no need to call showB() on changing health list.
EDITED (Optimized Code):
The following code has been altered from your source.
Mainpage
<html>
<head>
<script type="text/javascript">
function showBlock2()
{
var str11=document.getElementsByName("h")[0].value;
var str22=document.getElementsByName("yr")[0].value;
document.getElementById("txtHint").innerHTML="";
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getblock2.php?q="+str11+"&h="+str22,true);
xmlhttp.send();
}
</script>
</head>
<body>
Select a Health block
<select name="h" onChange="showBlock2()">
<option value="1">H1</option>
<option value="2">H2</option>
</select>
<br/>
Select a year
<select name="yr" onChange="showBlock2()">
<option>2012</option>
<option>2013</option>
</select>
<div id="txtHint" style="width:570px; height:auto" >
</div>
</body>
</html>
Note that only function showBlock2() is used for onchange on both dropdowns, so the div txtHint is updated at each change. Also no parameters passed.
Just remove
showB()
It will work fine. As you have already values in both variables. Just showB() function is making the variable empty again.
Here is the optimized code. It can work in both cases, which ever select option you select first.
<script type="text/javascript">
var healthValue = "";
var yearValue = "";
function showB(str2)
{
healthValue = str2;
if(yearValue != '')
{
callAjax();
}
}
function showBlock2(str)
{
yearValue = str;
if(healthValue != '')
{
callAjax();
}
}
function callAjax()
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getblock2.php?q="+healthValue+"&h="+yearValue,true);
xmlhttp.send();
}
</script>
I've been trying to use AJAX and PHP to create a dynamically changed form where selecting an index on the drop down box automatically changes the type of input that is displayed on the form. I use a select box on the form that onchange() submits to the AJAX function. The function uses XML to call the PHP file. The the 2 types of inputs that I'm trying to switch between are a file upload and a drop down box that is populated by data that I have on a remote database. When I select the option for the file upload input, it displays fine, but the PHP database drop down box does not display when I select that option.
Can anybody tell me what I'm doing wrong?
Here is the code I have right now:
File Name: test.php
<html>
<body>
<head>
<script>
function getInputs(str) {
var xmlhttp;
if (str == "") {
document.getElementById("display").innerHTML = "";
return;
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("display").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "grabtest.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<form action="">
<select id='RecipeSelect' onchange='getInputs(this.value)'>
<option selected value=''>Select</option>
<option value='N'>New file</option>
<option value='E'>Existing file</option>
</select>
<br>
<div id="display"></div>
<br>
</form>
</body>
</html>
File Name: grabtest.php
<?php
$q=$_POST["q"];
//connect to database on server
$con=mysqli_connect("connection","loginname","password","DBname");
//if there was an error in connecting to the database, display the error
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($q=""){
echo "";
}
elseif ($q="N"){
echo "Select file to upload: <input type='file' name='newfile'>";
}
elseif ($q="E"){
//creates a dropdown box where you can select desired field
$list = mysqli_query($con, "select * from TableName");
echo 'Recipes: <select name = "name">';
while ($row = mysqli_fetch_array($list))
{
echo '<option value = "' . $row["ID"] . '">' . $row["Recipes"] . '</option>';
}
echo '</select><br>';
echo '<input type="submit" value="Submit">';
echo '</form>';
}
mysqli_close($con);
?>
You are passing q in the query string and using POST. You need to either use GET or send q, in the send method of the XHR.
I am trying to setup a table on my site that is populated based on the users selection of from a drop down menu. The dropdown menu should make up the variables that will perform the SELECT statement.
To do this I have a HTML drop down and a AJAX function. This the function ...
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("loadhere").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("loadhere").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxtest.php?q="+str,true);
xmlhttp.send();
}
</script>
And this is the HTML
<form action="">
<select name="users" onchange="showUser(this.value)">
<option value="">Please choose</option>
<option value="1200">Courses</option>
<option value="">TEST</option>
<option value="">TEST</option>
<option value="">TEST</option>
</select>
</form>
<br>
<div id="loadhere"><b>Details will be listed here after selection.</b></div>
This then calls a php script
$q=$_GET["q"];
$sql="SELECT * FROM clntcoursetbl WHERE mbrid = '".$q."'";
$result = mysql_query($sql);
echo "<table id='box-table-b'>
<tr>
<th>Course</th>
<th>Start Date</th>
<th>Finish Date</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['course'] . "</td>";
echo "<td>" . $row['startdate'] . "</td>";
echo "<td>" . $row['finishdate'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
Currently I have a value of 1200 against the select option of 'course' , this is the client ID of the user and was just for testing to make sure everything works. Which it does.
Now , I would like to change it so that the value in the select is put into the SELECT statement to choose the table to search.
Something along the lines of "SELECT * FROM selected value WHERE mbrid = '".$q."'";
Is this possible ?
If so, how can I can I then also make the mbrid dynamic ? Can I pass a session variable into the function perhaps ??
As always , thanks for you help !
You can have an ajax call in the showUser() function which can go like this.
var url = "url of the file you want to get data from";
var e = document.getElementById("#<Your Select Items ID>");
var data = 'q='+e.options[e.selectedIndex].value;
$.ajax({
type: "post",
url: url,
data: data,
success: function(msg) {
}
});
Then you can use $_POST['q'] to get the value in your destination page.
Also try appending all your echo data to a variable and do an echo when you loop execution is complete.
<script type="text/javascript">
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
//document.myForm.text1.value=.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getuser.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form name="myForm">
<p>Selec the Menu :
<select name="users" onchange="showUser(this.value)">
<option value="">Select ID</option>
<?php do { ?>
<option value="<?php echo $row_rscustomer['customer_number']?>"><?php echo $row_rscustomer['customer_number']?></option>
<?php } while ($row_rscustomer = mysql_fetch_assoc($rscustomer));
$rows = mysql_num_rows($rscustomer);
if ($rows > 0) {
mysql_data_seek($rscustomer, 0);
$row_rscustomer = mysql_fetch_assoc($rscustomer);
} ?>
</select>
</p>
<p> </p>
<p>
<input name="text1" type="text"
value="<?php include (" getuser.php");?>"/>
<p>
</form>
<div id="txtHint"></div>
Hey - I noticed that, inside your AJAX onreadystatechange function, you have added xmlhttp.status==200 to your conditional. In some browsers, as AJAX is a client-side language, this isn't supported. If the member status isn't supported by the user's browser, then its default value will either be undefined or 0, either way the value will never be 200, thus the block inside that conditional won't be executed.
I suggest removing the xmlhttp.status==200 condition, and just relying on xmlhttp.readyState. I had this problem when I first started with AJAX.