Below is how i made my select option list
<select id="roomtype" name="roomtype" class="form-control select-block">
<?php
// Populate dropdown list of room types
$room = new Rooms;
$room_types = $room->Bind_Room_Types();
foreach ($room_types as $key => $value)
{
echo '<option id="roomtypeoption" value="'.$key.'">'.$value.'</option>';
}
unset($room);
?>
</select>
Now on an update request i made an ajax call which in return gives me a json data like below
[{"id":"1","roomno":"102","floor":"2nd","beds":"2 beds","roomtypeid":"1"}]
After getting the response i populated all the values on my form fields like below
success: function(response) {
// Taking ajax response into javascript objects to fill the form fields
console.log(response);
var object = {};
object = $.parseJSON(response);
$("#roomid").attr('value', object[0].id);
$("#roomnumber").attr('value', object[0].roomno);
$("#roomfloor").attr('value', object[0].floor);
$("#roombeds").attr('value', object[0].beds);
$("#roomtypeoption").remove(); // not working
$("#roomtypeoption").attr('value', object[0].roomtypeid); //not work.
$("#submit").attr('id', 'update').off('click');
}
now in case of text fields its working fine , but when i came to select tag it is not getting updated.
2nd problem is that as you can see in my json i have pasted above. there is 'roomtypeid:1'. This is actually a foreign key. What i want is when my select list get updated on success of ajax then 'roomtypeid' should be placed in How to display the value against foreign key (roomtypeid)
I'm lost in this :(
Please help thanks
I changed my approach. Closing the question.
Related
I have a form to insert data into a MySQL table that uses two drop down menus. The first is a list of parks and the second a list of rides. The second drop down box should only display items linked to the first by the column 'park_id'. I need a simple way for the second box to populate based on the first's selection.
This is the form so far:
<tr><td>Select Park:</td>
<td><select name="park_id">
<option value="">Select Park</option>
<?php foreach ($res as $row) {
printf('<option value="%s">%s</option>' . PHP_EOL, $row['park_id'], $row['name'] );
} ?>
</select></td></tr>
<tr><td>Select Ride:</td>
<td><select name="ride_id">
<option value="">Select Ride</option>
<?php foreach ($res2 as $row2) {
printf('<option value="%s">%s</option>' . PHP_EOL, $row2['ride_id'], $row2['name'] );
} ?>
</select></td></tr>
So somehow a query needs to run after selecting a park and use '$park_id = $row[park_id]' to help generate the results for the 'Select Ride' dropdown.
This is the query I need to use for the second drop down:
$qry2 = "SELECT ride_id, name FROM tpf_rides WHERE park_id = $park_id ORDER BY name ASC";
Can anyone talk me through this? Also my skill are very limited so a relatively simple solution would be great.
Thanksark
For this you will have to get into AJAX, and I highly recommend using jQuery's implementation. You will also need to get a good grip on JSON string coding and decoding.
The basic Idea of your code will be like so:
// listen for user to change the <select> item
$('select#park').on('change', function(){
$.ajax({
url: 'getrides.php' // send a park id to this script
,cache: false // do not cache results in browser
,type: 'POST' // send POST to getrides.php
,data: {'park_id': $('select#park').val()} // getrides.php will receive $_POST['park_id']
,dataType: 'json' // this AJAX call expects a JSON string as a return value
,success: function(data){ // the data variable will be converted to an array from JSON
// check out all your data
console.log(data);
// loop through your array
$.each(data, function(index, info){
// see your array indexes
console.log(index);
// see data in each array item
console.log(info);
});
}
});
UPDATE
You can also load all of the parks and rides into a Javascript array and based on what the user chooses from the dropdown then populate the second dropdown with those array members.
<script>
var rides = new Array();
rides['park1'].push('ride1');
rides['park1'].push('ride2');
rides['park1'].push('ride3');
rides['park1'].push('ride4');
rides['park1'].push('ride5');
rides['park2'].push('ride1');
rides['park2'].push('ride2');
rides['park2'].push('ride3');
rides['park2'].push('ride4');
rides['park2'].push('ride5');
// listen for user to change the <select> item
$('select#park').on('change', function(){
// clear current DD options
$('select#rides').html();
// loop through array of available rides for selected park
$.each(rides[''+$(this).val()+''], function(index, value){
// dynamically create the proper DD options
$('select#rides').append('<option>'+value+'</option>');
});
});
</script>
you have to write another file that uses the id of the first selected from the bikes list value to load the options of the second select tag the rides list
then make an empty div on the first file that will be loaded with the result of the second file which is the list of rides
$(function() {
$('#ID_of_the_park_selecttag').change(function() {
var value = $("#ID_of_the_park_selecttag").find('option:selected').text();
$("#ID_OF_THE_DIV").html("");
$("#ID_OF_THE_DIV").load('theOtherFile.php', {"bikename":value } );// value is the value of the select option from the first <select tag>
});});
then on the second file you can get the value of the bike selected as $_POST['bikename'] and do your query then fill the list
I had to do this recently myself. Here's what I did, feel free to use what makes sense to you. I tried what seemed like a simple way to myself.
<select name="department_list" id="department_list" onchange="$('#singleUser').load('yourextraphppage.php?nid='+this.value);">
<option value='none'>Select a department</option>
Then load your first select list with data and close the select tag... Add a blank div where you want the 2nd select. I used the value from the first select list for my parameter for the 2nd select list's query. (it was the foreign key in the 2nd table for the 2nd select list)
<div id="singleUser" class="singleUser">
</div>
Last, you need the additional PHP page that you called from the first select list. Here's a barebones version of my code.
echo "<option value='none'>Select user</option>";
try {
$db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stmt = $db->prepare("SELECT dm.empid AS empid, u.name AS name FROM mytable dm
JOIN mytable2 u ON dm.empid = u.id
WHERE dm.deptid = :id
ORDER BY u.name");
$stmt->bindParam(':id', $id);
$stmt->execute();
while ($r = $stmt->fetch()) {
$empid = $r['empid'];
$userName = $r['name'];
echo "<option value='".$empid."'>".$userName."</option>";
}
echo "</select>";
echo "</p>";
$db = null;
}
catch (PDOException $ex) {
echo "An Error occurred!";
}
I hope this helps. I'm rather busy so I can't go in detail explaining it at the moment. I'll check back later to see if you have any questions.
I was helping somebody a similar page a day or say ago:
2 dropdown selects and the list of options in the second dropdown changed according to the choice selected in the first.
The solution involved the use of <optgroup> elements within the <select> and jQuery (which is not all that easy for a beginner but at least you can copy the code.
See here for the question: jQuery - on page load select optgoup and children in second select by a default selected option in a parent select
And here to see the code in action here: http://jsfiddle.net/goodegg/phj8q/
(although there is a mistake in it).
EDIT
Go here for my forked version of the code: http://jsfiddle.net/annabels/7xksa/
Hey guys i am a newbie to php.What problem i am facing is i have created a dropdown which is populated from the data from database using this code.This is working fine for me and it is populating dropdown too
include('connect.php');
$query="select * from faculty";
$result=mysql_query($query);
while($row = mysql_fetch_assoc($result))
{$dropdown.="\r\n<option value='{$row['Designation']}'>{$row['Designation']} </option>";}
echo "<select>".$dropdown."</select>";
Solution i want is,when a user selects a value from dropdown,result should be retrieved from database and should be displayed in table.Please help me guys
You have to basically :
1) Perform a form sending to some server side script(PHP in your case) when there is a change in the dropdown selection (use onchange event for the dropdown) and fetch the values from the db ,
2) Tell the server side script to spit out an html string which contains the table containing the desired information.3) 3) Output the string on your page.
This will do a page refresh.
If you donot want to have a page refresh, resort to using Ajax.
P.S. I recommend using some framework such as jQuery in case you need to use Ajax
What you have to do is something like this:
In your Html:
<select onchange="fetchContent()">
<option id="1_Designation">abcd</option>
<option id="2_Designation">1234</option>
<option id="3_Designation">lkjh</option>
</select>
In your javascript:
fetchContent()
{
id = $(this).id;
$.ajax({
type: "POST",
url: "/path/content.php?id="+id,
success: function(response) {
$("#tableRow").html(response);
}
});
}
In content.php you will have to get the value of id and then do the necessary data retrieval and then return the data.
$id = $_POST['id'];
//retrieve the data to $data
echo $data;
Have been looking around for a solution to this and have found some help on stack overflow but in most cases the examples I have found are not using arrays formed from a database query. Here is some code for what I am trying to achieve...
$stores = mysql_query("SELECT * FROM Stores");
$staff = mysql_query("SELECT * FROM Staff");
I would like to create two elements, one for stores and another for staff but I want to filter the staff based on the store client side. So if the user selects "Sydney" from the first dropdown, they are presented with only staff that work at the Sydney store in the second dropdown. Then if the user chooses "London" from the first dropdown, the Sydney staff are replaced by the London staff and so on.
My server side scripting is done with PHP and I am able to create the two dropdowns with PHP. But I am stuck on the jQuery to remove the I don't want from the second dropdown.
I know this is possible, because I see it used all the time. I have seen lots of examples of how to manage this but none of the examples use data from the PHP array to insert the .
You need ajax.
When the user selects something in a dropdown, this fires an event that you can process. Inside of this process you take the value of the selection like jQuery('#id_dropdown').val(), and send this via ajax (I like using POST since you dont run into GET request size limits).
You process this on the server side with php, accessing to the database with the value selected and sent via ajax. When you have the right results for the second dropdown you can output it via echo.
Finally, when the response is returned to jQuery, you can insert all the options in the new dropdown.
JAVASCRIPT PART:
Bind event to the first dropdown
Get value of the option selected in the dropdown
Make ajax request
Here is some example code:
var parameters='value_selected='+value_dropdown;
jQuery.Post({
url: '/destiny_when_I_process',
data: parameters,
success: func_callback
});
//here you can imagine a pause, because PHP is processing the data you send by post
//....
//....
//this part is executed when php send the information
function func_callback(response_from_php){
jQuery('#second_dropdown').html(response_from_php);
}
PHP PART:
get value from POST
access database using this value
echo (send response). You send a chain of text (in HTML), really this is not very professional, but is OK for demonstration purposes. Professionals send JSON, since JSON is lighter-weight.
JAVASCRIPT PART (SECOND PART)
in the callback function, you receive the response data via the first parameter
Insert new data in the second dropdown (since the data is already HTML, you do not need to process it)
for the secondary drop down, yes, you'll need some ajax.
You can create a script that go fetch the result coresponding to the store and send back the option listm witch is inserted in the ooption.
Using jquery and php you'll need a few thing.
A php file to get the result and return the options. (let say getStaff.php)
<?php
//get the store id by post is it is set
if (isset($_POST['store->id']) $store_id = mysqli_real_escape_string($_POST['store_id']);
//get the data !! notice the WHERE caluse
$r = mysql_query("SELECT * FROM Staff" *WHERE store=''$store->is*);
//split the data in the array
$staffs=array();
while ($assoc = mysql_fetch_assoc($r)) {
//Varialbe = $assoc['colum_name'];
$staff->id=$assoc['id'];
$staff->name=$assoc['name'];
//and so on for each colum in your table.
array_push($staffs, $assoc);
}
//echo the result as option
foreach ($staffs as $staff) echo "<option value='$staff->id'>$staff->name</option>";
?>
In you first select, add
onchange="$.post('getStaff.php', {store_id:$(this).val()}, function (data){ $('#staff_select').html(data);});"
and add an id to your second select (staff_select) in this ecample.
As an explanation: When the 1st dropdown change, it send a request to getStaff.php with the store_id as a POST argument. The php sript get the syaff according to the store Id and bring back a list of option tags for your secondary select. Than jquery add the 'data' to your secondary select and VOilĂ !
Hope tih sis clear cause it's a bunch of little thing together that will make it work. Sorry if it's seems sloppy as an answer but it's really simple once you know it.
Spent the afternoon learning how to do this and it's working quite well. Posted the new code here for others....
Thanks to http://forum.codecall.net/topic/59341-php-sql-jquery-and-ajax-populate-select-boxes/ for the tutorial.
And thanks to everyone here.
PHP to build for the first :
function agency_select() {
include('../include/dbase.php');
$agencies = $pdo->query("SELECT * FROM agency WHERE Status='active' ORDER BY AgencyName");
$opt = '';
while ($age_array = $agencies->fetch(PDO::FETCH_ASSOC)) {
$opt .= '<option value="'.$age_array['AgencyId'].'">'.$age_array['AgencyId'].' - '.$age_array['AgencyName'].' - '.$age_array['AgencySuburb'].'</option>'."\n\t\t\t\t\t\t\t";
}
return $opt;
}
HTML for the two elements:
<label for="AgencyId">Client/Agency:</label>
<select class="uniform" id="AgencyId" name="AgencyId" style="width: 400px; overflow-x: hidden">
<?php echo agency_select(); ?>
</select>
<label for="Contact">Contact: </label>
<select class="uniform" id="Contact" name="Contact" style="width: 300px; overflow-x: hidden">
<option value="">----Select Client/Agency----</option>
</select>
AJAX file:
if(isset($_POST['AgencyId'])) {
include('../include/dbase.php');
$option = '<option value="">----Select Contact----</option>';
$query = $pdo->prepare("SELECT * FROM client WHERE AgencyId= ? AND Status='active' ORDER BY FirstName");
$result = $query->execute(array($_POST['AgencyId'])));
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$option .= '<option value="'.$row['id'].'">'.$row['FirstName'].' '.$row['LastName'].'</option>';
}
echo $option;
}
jQuery:
$(document).ready(function () {
update_contacts();
});
function update_contacts() {
$('#AgencyId').change(function() {
$('#Contact').fadeOut();
$('#loader').show();
$.post('../ajax/ajax_contact_select.php', {
AgencyId: $('#AgencyId').val()
}, function (response) {
setTimeout("finishajax('Contact', '"+escape(response)+"')", 400);
});
return false;
});
}
function finishajax(id,response) {
$('#loader').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
i'll try to help you as much as i can a explain it.
mysql_query, you sould use mysqli btw, mtsql being decrecated, return a result set.
This means you will have all the records from your query. You need to brak down your result into before you can work with it. This is done by using methids like mysql_fetch_assoc, mysql_fetch_row, etc. There something like fetch to array to but i don't master it so i will use fetch assoc, for this reply.
So once you have yoru result set, $stores & $staff in your case, you then call a while loop on your results to get th data as in:
while ($assoc = mysql_fetch_assoc($r)) {
//Varialbe = $assoc['colum_name'];
$stores->id=$assoc['id'];
$stores->name=$assoc['name'];
//and so on for each colum in your table.
array_push($stores, $assoc);
}
Then you can export it as you want.
in you case would be something like
foreach ($stores as $store) echo "<option value='$store->id'>$store->name</option>";
I storngly suggest you take alook at http://php.net/manual/en/function.mysql-fetch-array.php witch will do the same a fetch_assoc bu with an array with the columname as key.
On php page in a form, one combo-box has list of customers from a MySQL table customer. Another combo-box contains invoiceno fields from the invoice table, respective to customer records.
I want to select a customer from the first combo box and filter invoiceno from the second one according to the customer. Can anyone help me accomplish this?
For example, if I select customer1, the second combo box should show all invoiceno respective to the customer1. I want to do this without refreshing, reloading, or POSTing the page. If I get the first selection in a php variable $customer, it's enough for me. Thanks!
AJAX is your friend:
Capture onchange event of the first combo box
Then send the value of the selected item via AJAX to your PHP script
Your PHP script loads the corresponding values from the databases and returns them (for example in JSON format)
And finally you display/insert the returned data via JavaScript.
Pseudo code:
JavaScript:
function displayData(json)
{
// Do something
}
document.getElementById("your-combobox").addEventListener("change", function()
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState==4 && xhr.status==200)
{
displayData( JSON.parse(xhr.responseText) ); // Call displayData with the JSON
}
};
xhr.open("GET", "your-script.php?combobox1="+encodeURIComponent(this.value));
xhr.send(null); // Send AJAX request
});
PHP:
<?php
if (!isset($_GET['combobox1'])) exit('{}');
$data = GetDataFromDB_AsArray();
echo json_encode($data);
?>
I am new to PHP and I am trying to learn how to re-populate a dropdown once a new category has been added.
Right now the user can create a new category and a message is sent back on success. I am lost on how to re-populate the drop-down on success.
Here is some related code:
//Handles the submit to DB
$.post("addHourlyScheduleCB.php", {
schedule: $("#schedule").val()
},
function(list){
$("#message").removeClass().html(list);
//inject the latest drop down info
$("#scheduleSelect").load("scheduleSelect.php");
$("html,body").animate({scrollTop:0},'slow');
$.unblockUI()
}
);
On success I tried to inject the with a PHP page that pulls the updated data from the DB.
Here is the HTML
<select name="scheduleSelect" id="scheduleSelect">
<?php
while ($row = $db->sql_fetchrow($rateScheduleSQLresult)) {
echo "<option value=".$row['Rate_Schedule_ID'].">$row[schedule]</option>\n";
}
?>
</select>
Here is the page that is called in the success function of the jQuery:
<?php
require_once("models/config.php");
$rateScheduleSQL = "SELECT * FROM rateschedules ORDER BY schedule";
$rateScheduleSQLresult = $db->sql_query($rateScheduleSQL);
while ($row = $db->sql_fetchrow($rateScheduleSQLresult)) {
echo "<option value=".$row['Rate_Schedule_ID'].">$row[schedule]</option>\n";
}
?>
*EDIT: The initial dropdown shows the expected results. It is one the success of the post that the dropdown shows no results. I believe this is an issue of how I am trying to update the dropdown. I believe there must be a much better way. *
Within your callback, try seeing what is actually returned by the AJAX call. Add console.log(list) to make sure something is returned (this will show in your developer tools/firebug console).
The .load() function is an event handler, it acts when the called-upon element (#scheduleSelect) is loaded, it doesnt populate it with any info.
You want to make another $.post call to get the data from scheduleSelect.php, and populate the dropdown with the callback variable. (try to do a console.log(variable) with the 2nd post)