At the moment I using a dynamic select to populate a dropdown. What I would like to do is display a 2nd dropdown with results based on the selection of the first. I have no idea how to go about this and have searched for an answer but to no avail. I have included the code I using to populate the first menu, and if you need any further code, please let me know. I am quite willing to look at jQuery or javascript if someone could help with the code. Many thanks
<form id="boxform" method="post" class="webform" name="boxform" />
<label for="company">Select a Company:</label>
<select name="company" id="company" />
<option SELECTED VALUE="">Select a Company</option>
<?php
do {
?>
<option value="<?php echo $row_Recordsetcust['customer']?>"><?php echo $row_Recordsetcust['customer']?></option>
<?php
}
while ($row_Recordsetcust = mysql_fetch_assoc($Recordsetcust));
$rows = mysql_num_rows($Recordsetcust);
if($rows > 0)
{
mysql_data_seek($Recordsetcust, 0);
$row_Recordsetcust = mysql_fetch_assoc($Recordsetcust);
}
?>
</select>
UPDATE:
This is the code for the 2nd dropdown in php format that I have at the moment if it would help move on with this, thanks
<label for="boxrtnaddress">Select Address</label>
<select name="boxrtnaddress" id="boxrtvaddress" />
<option SELECTED VALUE="">Select Delivery Address</option>
<?php
while ($row_rs_select_address2 = mysql_fetch_assoc($rs_select_address2))
{
$value=$row_rs_select_address2['address1_com']. " ". $row_rs_select_address2['address2_com']. " ". $row_rs_select_address2['address3_com']. " ". $row_rs_select_address2['town_com']. " ". $row_rs_select_address2['postcode_com'];
$caption=$row_rs_select_address2['address1_com']. " ". $row_rs_select_address2['address2_com']. " ". $row_rs_select_address2['address3_com']. " ". $row_rs_select_address2['town_com']. " ". $row_rs_select_address2['postcode_com'];
echo "<option value=\"", $value, "\">", $caption, "</option>";
}
?>
</select>
+++++++++++++SOLUTION++++++++++
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
$("#company").change(function() {
if ($(this).val()!="") $.get("getOptions.php?customer=" + $(this).val(), function(data) {
$("#divId").html(data);
});
});
});
</script>
getOptions.php
<?php
$customer = mysql_real_escape_string( $_GET["customer"] ); // not used here, it's the customer choosen
$con = mysql_connect("localhost","root","");
$db = "sample";
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db, $con);
$query_rs_select_address2 = sprintf("SELECT * FROM company_com where idcode_com = '$customer'");
$rs_select_address2 = mysql_query($query_rs_select_address2, $con) or die(mysql_error());
$row_rs_select_address2 = mysql_fetch_assoc($rs_select_address2);
$totalRows_rs_select_address2 = mysql_num_rows($rs_select_address2);
$address=$row_rs_select_address2['address1_com']. " ". $row_rs_select_address2['address2_com']. " ". $row_rs_select_address2['address3_com']. " ". $row_rs_select_address2['town_com']. " ". $row_rs_select_address2['postcode_com'];
echo '<select name="customer">'.'<option value="">Select delivery address</option>'.'<option value="address">'.$address.'</option>'.'</select>';
?>
it may help, here is a fiddle
http://jsfiddle.net/gZzQr/
that dynamically appends a select based on the selection of first select the code is messy and dirty so im not gonna post it here :)
you can have a look at the following to better understand the working
change triggers when the selected value of a select is changed
is(':empty') checks whether the div to which the newly created `select
is to be appended is empty or not
http://api.jquery.com/is/
http://api.jquery.com/empty/
Edit
i'll give you hints hopefully you'll fill in the rest of code...
first of all what you need to do is handle the change event of your first drop down and when the value changes you can do an ajax, get, post request to your server, fetch the results and populate the second drop down, here is a useful stackoverflow link that may help you
php dropdown menu population
$("#firstDD").change(function(){
var value = $(this).val();//get the changed value of first dd(drop down)
//now do a post request
$.post("results.php",{data:value},function(data){
//get the values here and populate the second drop down
});
});
in your results.php
get the value from first drop down
$val = $_POST['data'];
//now do the sql queries to fetch desired result
//and echo the results back
echo $results ;
here are some useful links
http://www.prodevtips.com/2008/08/15/jquery-json-with-php-json_encode-and-json_decode/
http://api.jquery.com/jQuery.post/
http://www.factsandpeople.com/facts-mainmenu-5/26-html-and-javascript/89-jquery-ajax-json-and-php
Related
I've been reading lots of questions at stackoverflow that have made my life easier, first time I ask something though.
Here is my problem. I need to be able to insert different values from my SQL database into a selected < textarea > field, depending on what option is selected in a < select > input on the same form.
The basic idea is that I want to edit news from the database, edit title and body. To do that, I want to show what (title / body) data contains my db to the user, by getting them from my SQL db. User may have multiple entries in the database, so when I select one entry at the < select > combobox, I'd like to change the contents to those from the selected entry from the db.
Its a simple idea difficult to express due to my poor English...
HTML form would be more or less as follows:
<form action="edit.php" method="post">
<select name="id">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<textarea name="newsBody"></textarea>
<input name="submit" type="submit" value="Edit" />
</form>
SQL database structure goes more or less as follows:
DB name: database
DB table: news (fields id, body, title, author, timestamp)
I'd like to be able to select news from my < select > getting their 'id' / 'option value', then get from the DB the corrrect value, and show it in the corresponding < textarea >.
I'm new into website coding, and do it just as a hobby, so my knowledge in PHP, MySQL is very basic. I dont provide any PHP code or options, simply because I have no idea how to resolve it... I can understand sql, php syntax though.
I thought using < select > event 'onchange' and javascript, but couldn't make it work... Neither could I using jQuery / ajax, probably because the lack of useful examples!!
Hope that someone understands and can provide a solution!
Many thanks in advance!
You can use Ajax.
Create the following .html page:
<html>
<head>
<script>
function showData(str)
{
if (str=="")
{
document.getElementById("ajax-content").innerHTML="";
return;
}
// Code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// Code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax-content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showData.php?id="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="news" onchange="showData(this.value)">
<option value="">Select ID:</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
<div id="ajax-content"></div>
</body>
</html>
And the following .php script (showData.php in my example):
<?php
// Receive variable from URI
$id=$_GET["id"];
// Connect to your database
$con = mysql_connect('localhost', 'user1591005', 'stackOverflow');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db("myDatabase", $con);
// Select all fields from your table
$sql="SELECT * FROM news WHERE id = '".$id."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<input type='text' value='" . $row['title'] . "'>";
echo "<textarea>" . $row['content'] . "</textarea>";
}
// Close the connection
mysql_close($con);
?>
Alright Ill give you a quick idea before my lunch... :)
Setup an AJAX request to pass the selected dropdown box value to a PHP script.
In this PHP script, fetch the data for the selected value from your database.
Return the data and set the textbox's value to that.
Sending an AJAX Request
It seems that you need to use AJAX and Mysql+PHP for this. The first thing is to collect data from the table.
for example $result = mysql_query('SELECT * FROM new_table WHERE author = author's id')
The second thing is to output the html code with the results from the table you could use
you can do this by using foreach() loop. Then you need to use ajax (from the jQuery framework) and to pull data from the database again on user selection.
Hope this helps
To get the data from the database, you'll have to use a server-side language, such as PHP. To react to the change in the <select> element, you'll have to use JavaScript. AJAX is what will bridge the gap between the two languages.
Firstly write some JavaScript to make the query. If you're using jQuery, this is very straightforward.
<script>
var selector = $("#mySelectorID"); // first select the <select> elm
selector.change(function(e) { // attach a function to it's change event
jQuery.get("getContents.php", // when it changes, make an AJAX call
{id:selector.val()}, // passing the value of the <select> as data
function(returnVal) { // after a successful AJAX ...
$("#myTextAreaID").val(returnVal); // ... set the textarea to the correct value
});
});
</script>
Then create a new php file (slightly simplified, but this would work):
<?php
$id = $_GET['id']; // get the id that was passed through the URL
$connection = mysql_connect("hostname","username","password"); // connect to db
mysql_select_db("database", $connection ); // select the db
$result = mysql_query("SELECT * FROM news WHERE ID = $id"); // make SQL query
if ($row = mysql_fetch_array($result)) { // fetch the first row
echo $row['body']; // output the contents of the row
}
connection mysql_close($connection ); // close the connection
?>
More info on AJAX with jQuery: http://api.jquery.com/jQuery.get/
I am imagining you want to work on a simple html/PHP solution before branching out to Ajax ...
<?php
$title = "" ; // set the variables
$body = "" ;
$action = "" ;
$submit = "Edit";
if(isset($_POST['id']) && (int) $_POST['id'] > 0 ){
// a positive integer was sent to your form
// so now construct your sql statement: ie
// "select title, body from new where id= " . $_POST['id'] ;
// assign your rows to your variables
// $title = $row['title'] ;
// $body = $row['body'] ;
// now re-use your empty form to display the variables
// re-assign the form variables
// $action = "save.php" ;
// $submit = "Save changes";
}
?>
// have the form submit to itself by default
<form action="<?php echo $action; ?>" method="post">
<select name="id">
<option value="1" <?php if($_POST['id'] == 1 ) echo "selected=selected; ?>>Option 1</option>
<option value="2" <?php if($_POST['id'] == 1 ) echo "selected=selected; ?>>Option 2</option>
</select>
// have your html form values the same name as your db table columns
<input type="text" name="title" value="<?php echo $title; ?>"/>
<textarea name="body"><?php echo $body; ?></textarea>
<input name="submit" type="submit" value="<?php echo $submit; ?>" />
</form>
save.php then stores the new values in your database and perhaps redirects back to this page...
I am really paring this down, you'd likely generate your ids from a select from the database, and they'd probably be id, title in alphabetical order:
A big story
Big story
etc
There is lots else to take into consideration, but this is one way to go about it.
If you are using php with SQL to retrieve data from a database you can insert the database field using the following code.
echo '<textarea name="MyText" id="MyText" rows="8" cols="80" >' . $MySelectedText . '</textarea></p>';
Where MySelectedText is the data base field name of your SQL text you have selected from the database.
hope you can help as I'm starting to pull my hair out :) There seems to be loads of links around regarding this but I can't get any of them to work, so I'm just going to ask in straight laymans terms.
I have a database... it has fields for Region, Area, Manager, Employee
I have a front end form, with select boxes in it...
When you choose the Region, I need the Area selectbox to dynamically populate with the relevant areas from the database without refreshing the page
Then when the Area selct option is chosen the Manager one needs to populate. and so on.
No doubt this needs an ajax/ Jquery solution, of which as I've said there's many articles around about this but I just cannot get them to work. I've NEVER even attempt AJAX before today so sincere apologies if this is a total noob thing to be asking.
Any help or guidance would be greatly appreciated. Thankyou!
Okay I have this for my Jquery:
$(document).ready(function() {
$('#Region').change(function() {
// remove all options in Area select
$('#Area').html('');
// find the new Region selected
var selected_region = $('#Region').val();
// get new options from server and put them in your Area select
$('#Area').get('Ajax/getArea.php?Region=' + selected_region);
});
});
and this for my PHP:
<?php
// get province id passed in via `post` or `get`
$region = $_REQUEST['Region'];
// get the districts in that province
$query = "SELECT DISTINCT AREA FROM Sales_Execs WHERE Region ='$region'";
// link to your database
$link = mysqli_connect("localhost", "root", "", "Quality_Monitoring");
// execute your query
$result = mysqli_query($link, $query);
// parse the options
while($row = mysqli_fetch_assoc($result)) {
$options = "<option value=\"".$row['AREA']."\">".$row['AREA']."</option>\n ";
}
// send options
echo $options;
?>
And still no joy... can anyone spot what I'm missing?
try this, there are 3 different sections I have included in the code:
1) the PHP code
2) The jQuery
3) The select box container
:: Your PHP file (call it getArea.php)
$selectbox = '<select name="region" onchange="jQuery.selectRegion(this.value)">';
$region = $_REQUEST['Region']; /* Make sure you escape this */
$query = "SELECT DISTINCT AREA FROM Sales_Execs WHERE Region ='$region'";
$link = mysqli_connect("localhost", "root", "", "Quality_Monitoring");
$result = mysqli_query($link, $query);
$options = '';
while($row = mysqli_fetch_assoc($result)) {
$options .= '<option value="' . $row['AREA'] . '">' . $row['AREA'] . '</option>';
}
echo $selectbox;
echo $options;
echo '</select>';
exit;
:: Your jquery
jQuery.selectRegion = function selectRegion(regionId)
{
$.get('ajax/getArea.php?region='+regionId,function(data){
$('#select_container').html(data);
});
}
:: The select box container
<div id="select_container">
<select name="region" onchange="jQuery.selectRegion(this.value)">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
Hope this helps
I've been at this for hours and i have gotten a slight break through, however i am at a stand still at the moment. I have a SQL Database that store vehicle information, such as make, model and year. What i want to do is allow users to modify the query and only display specific results.
I understand how to display all the records at once but what i want to add is when the user selects say for example the make as "Toyota" i want only that specific make to appear. I did reach some where in this, by using this code:
<form method="post" action="">
<div id="search_query" >
Make
<select name="make" size="0">
<option value="honda">Honda</option>
<option value="toyota">Toyota</option>
<option value="nissan">Nissan</option>
</select>
<input type="submit" name="submit" value="submit">
</div>
</form>
<?php
$db_con = mysql_connect('localhost', 'root', '');
if (!$db_con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('my_db', $db_con);
$make = mysql_real_escape_string($_POST['make']);
$sql = sprintf("SELECT * FROM chjadb_vehicles WHERE v_make= '$make' ");
$result = mysql_query($sql);
echo "<table width= 970 border=1>
<tr>
<th width='120' scope='col'>Image</th>
<th width='170' scope='col'>Details</th>
<th width='185' scope='col'>Seller</th>
<th width='126' scope='col'>Price</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td> <img src=" .$row['v_image']. " width =200 height = 130>" . "</td>";
echo "<td>". $row['v_year'] . " " . $row['v_make'] . " ". $row['v_model'] . " ". $row['b_type']. "</td>";
echo "<td>". $row['user_id'] ."</td>";
echo "<td>". $row['v_price'] ."</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($db_con);
?>
however when i run the page initially i get this error: "Notice: Undefined index: make in C:\xampp\htdocs\carhuntja.com\buy_a_car.php on line 62"
i did some research and realized that this was happening because i had no make value set, what i wish to do here is at the start of going to that page i want all vehicles to be displayed.
The problem is that the query is being sent before the user chooses a make. To fix this, you need check that the user has actually submitted the form by enveloping your PHP code in if(isset($_POST['submit'])) ("submit" is used because that is the name of your submit button).
//place connection code here (do not query the database yet)
if(isset($_POST['submit']))
{
//all of the database retrieval code
}
else
{
$query_makes = "SELECT v_make FROM chjadb_vehicles";
$result_makes = mysqli_query($query_makes);
echo "Please choose a make."
//echo opening select tag
while($row = mysql_fetch_array($result_makes))
{
//echo each option tag
}
//echo ending select tag
}
Also, you are missing a slash in the self-contained input tag.
Finally, you should use MySQLi functions because MySQL functions are deprecated in PHP.
When the page loads for the first time you need to run this query:
SELECT * FROM chjadb_vehicles
You need to check if the user clicked the submit button and posted the make field, to do that use isset():
if (isset($_POST['make']){
$make = mysql_real_escape_string($_POST['make']);
}
I strongly suggest you use jquery and ajax
EDIT:
First time the page loads you display all vehicles.
In your javascript you bind a onSelect evvent to the dropdown and once the user selects a make, you send an ajax request to the server and display the new results from the server, so it'll look something like that:
$('#search_query select').change(function(){
//get the selected option text
var selectedVal = $(this).find('option:selected').text();
//send ajax request
$.ajax( {
url : url,
type : "POST",
data : selectedVal ,
dataType : 'json',
success : function(data) {//handle returned data}
})
});
I suggest you take a look here, for a complete VIDEO tutorial on jquery.
So, im creating a form that will submit data into an SQL database. Ive got 2 select drop downs that hold the data of "Module Code" and "Module Title". In the database a module title will only have one module code e.g Team project(module title) has module code 11COB290.
How can i get it so that when a user selects a given module name OR Module title is will automatically select the correct partner i.e select the right module code thats related to the module name the user has selected without pressing any submit buttons?
The following code is the drop down select boxes and php code i have so far:
<td align="center">
<select name='ModuleTitle' id='ModuleTitle' style='width:100%;'>
<option>Select...</option>
<?php
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row = mysql_fetch_array($result)) {
$module = $row[2];
echo "<option name='{$module}'>{$module}</option><br />";
}
?>
</select>
</td>
<td align="center">
<select name='ModuleCode' id='ModuleCode' style='width:100%;'>
<option>Select...</option>
<?php
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
ORDER BY `ModCode` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row = mysql_fetch_array($result)) {
$module = $row[3];
echo "<option name='{$module}'>{$module}</option><br />";
}
?>
</select>
</td>
Unless there is a special reason to do so, why not give a single SELECT box instead of two?
<td align="center">
<select name='ModuleTitle' id='ModuleTitle' style='width:100%;'>
<option>Select...</option>
<?php
//3. Perform database query
$result = mysql_query("SELECT * FROM Module ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row = mysql_fetch_array($result)) {
$module = $row[2] . ' (' . $row[3] . ')';
$moduleCode = $row[3];
echo "<option value='{$moduleCode}'>{$module}</option>";
}
?>
</select>
</td>
Or otherwise if you would like to keep 2 SELECTs, use AJAX calls. The idea is to define onChange event on each SELECT and in that event, send an AJAX request to a PHP script. The PHP script will request the module code or title and send it back to the AJAX handler. The AJAX handler can then automatically mark as SELECTED the corresponding option in the other SELECT. You might need sometime to research on AJAX and JavaScript if you aren't already experienced with this stuff.
Another idea might be to use the module code as the value for the title SELECT and module title as the value for the code SELECT. For example, title SELECT will be:
<SELECT name="ModuleTitle" id="ModuleTitle" style="width:100%;">
<OPTION>Select...</option>
<OPTION value="123">Title 123</OPTION>
<OPTION value="345">Title 345</OPTION>
<OPTION value="567">Title 567</OPTION>
</SELECT>
Then in the onChange event handler you might do something like this:
var selObj = document.getElementById('ModuleTitle');
var selIndex = selObj.selectedIndex;
document.getElementById('ModuleCode').value = selObj.option[selIndex].text;
By the way, there is no "name" attribute for . It should be "value" instead. Please fix in your code.
Hope it helps!
CAUTION: none of the above code is tested but I hope it works fine
I have a drop-down select tag for Patients:
<select>
<?php
$qPatient = mysql_query("SELECT idpatients, firstName, mi, lastName, suffix FROM patients ORDER BY lastName ASC");
while($rowPatient = mysql_fetch_array( $qPatient )) {
if(isset($rowPatient['suffix']) && !empty($rowPatient['suffix'])){$suffix = " " . $rowPatient['suffix'];}else{$suffix = NULL;}
if(isset($rowPatient['mi']) && !empty($rowPatient['mi'])){$mi = " " . $rowPatient['mi'] . ".";}else{$mi = NULL;}
echo "<option value=" . $rowPatient['idpatients'] . $rowPatient . ">" . $rowPatient['lastName'] . $suffix . ", " . $rowPatient['firstName'] . $mi . "</option>";
}
?>
</select>
This generates a list of patients from the drop-down.
How do I get the patientID based on the selection from my drop-down to put to my link?
ex: Update
where $idpatients = the patient ID from the drop-down list select tag.
Also, I need to have 3 different links: 1.) update.php 2.) chart.php and 3.) report.php
Set this form method to GET. After submiting, value of select field will be shown as get variable. So, add name to your select:
<select name="parientId">
And proper action to your form:
<form action="update.php" method="GET">
And, of course submit button.
This is "static way" with form". If you are sure that you want to have link, not submit button, you can do it with jQuery:
$("#go").click(function(){ $("#idOfYourForm").submit(); }
...
Go !
Or catch .change() (sorry, not select()) on your <select...> and set $("#go").attr('href','update.php?patientId='+$("#yourSelectId").val());
P.S.
Get from SQL only fields you need, not *
Update
<form...>
<select name="patientId" id="patientSelect">
...
</select>
<a id="updatelink" href="">....</a>
<a id="deletelink" href="">....</a>
<script type="text/javascript">
$(document).ready(function(){
$("#patientSelect").change(function(){
$("#updatelink").attr('href',"update.php?id="+$("#parientSelect").val());
$("#deletelink").attr('href',"delete.php?id="+$("#parientSelect").val());
}
});
</script>
Something like that, written fast, not checked/tested