Changing table for select statement based on dropdown with ajax function? - php

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.

Related

how can i link two drop down menu box where i can select one menu and it should show my list in other drop down box?

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>';
}
}
}

change form input through drop down box AJAX and PHP

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.

Populating dropdown list from d/base then using for ajax retrieval

I have a query relating how to combine a couple of elements:
a standard drop down select box whereby users can choose from a list of names sourced from a mysql database table.
upon selection from this box- an ajax function which retrieves further data and displays in a html table in a div further down the page. When a new name is selected from the dropdown- the table data refreshes
I can get both elements working individually but not together, i.e. when I write the names individually into the html select bit the javascript/ajax works, but when I implement the PHP to populate the dropdown list automatically the other data doesn't pull in at all.
Some code:
<head>
<?php
$con = mysql_connect("localhost","******","*******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*******", $con);
$sql="SELECT
People1.person_id,
People1.forename,
People1.surname,
People1.team_id
FROM People1
WHERE People1.team_id = 8";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["person_id"];
$thing=$row["forename"];
$options.="<OPTION VALUE=\"$id\">".$thing;
}
?>
<script type="text/javascript">
function showUser(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","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<h1>Player Info</h1>
<form>
<SELECT NAME="player_id" "showUser(this.value)">
<OPTION VALUE="">Choose</OPTION>
<OPTION VALUE=<?=$options?>></OPTION>
</SELECT>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
In all that above I'm getting the drop down to pretty much populate okay, but selecting names is not bringing anything through from the getuser.php file.
Your while loop should be the following
while ($row=mysql_fetch_array($result)) {
$id=$row["person_id"];
$thing=$row["forename"];
$options.="<OPTION VALUE=\"$id\">".$thing."</OPTION>";
}
And you select block should be the following
<SELECT NAME="player_id" onchange="showUser(this.value)">
<OPTION VALUE="">Choose</OPTION>
<?=$options?>
</SELECT>

Dynamic AJAX list not posting

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);
}

Why the ajax code works in IE, chrome, FireFox5.0 but not works in FireFox 3?

I got a simple AJAX demo code from internet which fills one select listbox dynamically with values from database. It contains a html file with AJAX code embedded in it and a PHP file.
The problem is this code works fine in IE, Chrome, FireFox4 but its not works in FireFox3. Please any one explain this and tell me the solution. The code is as follows for reference
The database schema for city table is as follows
id tinyint(4) primary key not null
city varchar(50)
countryid tinyint(4)
HTML File
<html>
<head>
<script type="text/javascript">
function getCity(strURL)
{
alert("inside getCity function");
//var req = getXMLHTTP(); // function to get xmlhttp object
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
//xmlhttp=new XMLHttpRequest();
req=new XMLHttpRequest();
}
else
{// code for IE6, IE5
//xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
req=new ActiveXObject("Microsoft.XMLHTTP");
}
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) { //data is retrieved from server
if (req.status == 200) { // which reprents ok status
document.getElementById('citydiv').innerHTML=req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n");
}
}
}
//alert(srtURL);
var sURL="findcity.php?country="+strURL;
req.open("GET", sURL, true); //open url using get method
req.send();
}
}
</script>
</head>
<body>
<form method="post" action="" name="form1">
Country : <select name="country" onChange="getCity(this.value)">
<option value="">Select Country</option>
<option value="1">india</option>
<option value="2">usa</option>
</select>
<br />City : <div id="citydiv">
<select name="select">
<option>Select City</option>
</select>
</div>
</form>
</body>
</html>
PHP file
<?
echo $_GET['country'];
echo "<br>";
$country=intval($_GET['country']);
echo $country;
echo "<br>";
$link = mysql_connect('localhost', 'root', 'mark'); //change the configuration if required
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('querytest'); //change this if required
$query="select city from city where countryid=$country";
echo "<br>";
echo $query;
echo "<br>";
$result=mysql_query($query);?>
<select name="city">
<option>Select City</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value><?=$row['city']?></option>
<? } ?>
</select>
Please guide me friends to make this code working in FireFox 3
Change
req.send();
to
req.send(null);

Categories