<select id="postnr" name="post_postnr" onChange="updatePlace()">
<?php do { ?>
<option value="<?php echo $row_postnr['postnr'] ?>" ><?php echo $row_postnr['postnr']?></option>
<?php } while ($row_postnr = mysql_fetch_assoc($postnr));?>
</select> <div id="place" style="display:inline"></div>
When user changes value in dropdown, I want to search a database (same table) for the corresponding place and paste it into innerHTML of #place.
The values for the dropdown is collected from a SQL table, column postnr.
postnr place
-----------------
1234 Place1
3456 Place2
and so on...
So when 1234 is selected, Place1 should pop up next to it.
Very basic question about the use of AJAX.
updatePlace() should be a Javascript method that will make an AJAX request to a specific PHP page. This page have to connect to the database and get all needed values.
Take a look at this sample to have a clearer idea.
Hope that helps
If you are using jQuery, you can use the following (the way to do it is the same without jQuery):
<script type="text/javascript">
$("#postnr").on('change', function(){
$.get('get_place.php', {postnr: postnr}, function(data){
$("#place").html(data);
});
});
</script>
Then create a *get_place.php* file with something like the following:
$query = mysql_query("SELECT * FROM places WHERE postnr='".mysql_real_escape_string($_GET['postnr'])."'");
$row = mysql_fetch_assoc($query);
echo $row['place'];
Related
Having a difficult time trying to suss this out. I've searched through, but I'm not sure if the phrase I'm using to search is correct or not.
I have a JSON file that I'm using to bring in an array of data from an outside source. Using PHP, I decode the contents. I've created a dropdown box that will display the keys, but what I'm looking to do now is dynamically populate a printout with the different values that the keys are attached to based on what the select box has selected.
<?php
// JSON string
$json = file_get_contents("showrace.json");
$races = json_decode($json, true);
?>
<select id="raceSelect">
<option value="select one" selected>Select One</option>
<?php foreach($races as $key => $value) { ?>
<option value="<?php echo $key ?>"><?php echo $value['race'] ?></option>
<?php } ?>
</select>
<div id="template">
Str Plus: # Dex Plus: # Wis Plus: # Int Plus: #<br>
</div>
And here is a sample of what the JSON file looks like:
{
"Ithorian":{"price":0,"wis":3,"str":2,"lck":0,"int":2,"frc":0,"dex":-2,"con":2,"cha":-3,"app":"No","hp":1200,"ac":0,"race":"Ithorian","lang":"ithorian"},
"Weequay":{"price":1000,"wis":-2,"str":3,"lck":0,"int":-2,"frc":0,"dex":0,"con":2,"cha":-3,"app":"No","hp":1350,"ac":0,"race":"Weequay","lang":"weequay"}
}
In the first snippet, the #'s in the template div will be outputs for the JSON values such as "str" and "dex" and such. While I was able to find out how to set the select to draw in the keys from the JSON, I am baffled at how to populate the template portion with the corresponding values, based off of the selected item.
Thanks in advance!
This may help you get started, as it is not fully fleshed out for everything. But it covers some basics you could use.
First off you would want an onchange handler in your jquery. This will fire off everytime someone changes their choice with the :
$("#raceSelect").change(function(e){
// magic will go here (see further below)
});
// or
$("form").on("change","#raceSelect",function(e){
// magic will go here (see further below)
});
Next up you would want to have access to all that json data in your jquery area to use for displaying those values based on what they chose:
<script>
// define this in your php page output near the top
// or within your jquery .ready block
var jsonData = <?PHP echo $json;?>;
</script>
Now you are ready to do some of the magic with the onchange. Accessing the right array in the jsonData, with the id chosen, you can swap out spans and divs to your hearts content. A combined example is as follows:
<?PHP
// your php script
$json = file_get_contents("showrace.json");
$races = json_decode($json, true);
?>
<!-- your form here as you have it in your example -->
<div id="template">
Str Plus: <span id="dat_str">#</span> Dex Plus: # Wis Plus: # Int Plus: #<br>
</div>
<script>
$( document ).ready(function() {
// this is your jquery .ready block
var jsonData = <?PHP echo $json;?>;
$("form").on("change","#raceSelect",function(e){
var race = $(this).val();
$("#dat_str").html( jsonData[race].str );
// you can set the dex, and wiz, etc as well
// following the same format to assign
});
});
</script>
Disclaimer: I hand typed this out, and didn't vett or test it. Its purely an example of pieces that should hopefully help you out.
you can do it using JS
var raceSelect = $('#raceSelect').find(":selected").text();
and check out this link on how te select from json
then print what you want
select from json
I am using php and getting data from mysql. I would like to have a dropdown of countries and then when the country is selected then the prefix must be the result either in a text box on the same line or just below the dropdown box.
so far my code gives me the prefix concatenated with prefix eg
Zimbabwe-263
here is the code
<?php
include 'config.php';
$query="SELECT countryname, countryprefix FROM cc_country";
$result = mysql_query($query);
$options="";
echo "<select name='processor' value=''>
<option>Select A Country</option>";
while($nt=mysql_fetch_array($result))
{
echo "<option value='".$nt['countryprefix']."'>".$nt['countryname']."-".$nt['countryprefix']."</option>";
}
If you want the selected value to display in textbox you can use jquery for that.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<sctipt>
$('select').change(function(){
var value=$(this).val();
$('#text').val(value);
});
</script>
Create a textbox with id text for this
You will need to fire another query that will fetch the country prefix on selection of the country.That is pass the value of your select box to he sql query.You can do this using jquery or javascript by giving an id to the select box you are using .
var countryname = $('#yourId').val();
then do a ajax or jquery post to a PHP file which will have the blow query.
For example:
$query="SELECT countryprefix FROM cc_country where countryname='your post value";
then below your while loop add a text field which will display the value returned by your above query
$('select').change(function(){
var value = $(this).val();
$('.textbox').val(value); // html <input type="text" class="textbox">
});
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;
see my client site first to get an idea.
In above site, i have a giftfinder box in right side. There are 3 select boxes. currently I'm using 3 forms for these 3 select boxes which means each drop down select box is embedded into form. When you select the first drop down select box, it picks one and second select box's value will be determined which value is selected from first select box. So if you choose Man, then all athe related occasions of Man will be dispalyed into seconds drop down select box. Its working fine.
But the problem is it refreshes everytime you select the first drop down box.
I don't want to refresh page. it must select the value and pass the value so seconds select box can determine its related values.
so I'm thinking to us ajax. but no success.
So i included some code for the first drop down select box.
this is mix of html and php and wordpress.
<div class="select-one">
<form id="searrec" method="post" action="">
<select name="selectionRecipient" id="selectionRecipient" onchange="this.form.submit();">
<?php
$results_rec = get_option('current_recipient');
if(isset($_POST['selectionRecipient'])){
$results_rec = $_POST['selectionRecipient'];
update_option('current_recipient', $results_rec);
$results_rec = get_option('current_recipient');
}
?>
<?php
//asort($result_rec);
$t_name_arr = array();
foreach($result_rec as $rec):
$t_id = $rec->term_id;
$term = get_term($t_id , 'category' );
$t_name_arr[] = $term->name;
endforeach;
//print_r($t_name_arr);
rsort($t_name_arr);
foreach ($t_name_arr as $t_name):?><option class="rec_val"<?php if($results_rec==$t_name){ echo 'selected="selected"';}?>value="<?php echo $t_name;?>"><?php echo $t_name;?></option>
<?php endforeach;?>
</select>
<input type="hidden" id="submitrec" value="Search" />
</form> -->
</div>
So I'm am using form method post and using $_POST to retrieve the selected value and pass it to $results_rec variable.
Later in the code, I'm using if.. else to determine if $results_rec =='Man' then display certain items which are related to Man and so forth.
So what I want is not to refresh the page while I select item from first drop down select box.
Please help.
change this:
<select name="selectionRecipient" id="selectionRecipient" onchange="this.form.submit();">
to this:
<select name="selectionRecipient" id="selectionRecipient">
and the jquery:
$("#searrec").submit(function(e) {
e.preventDefault();
// your code
return false;
});
EDITED:
use this to get the selected index (number)
var index = $("#selectionRecipient")[0].selectedIndex;
or value:
var value = $("#selectionRecipient")[0].value;
Then you can call an ajax perhaps: (assuming the other selection box has "id=other_select"
$.ajax({url:"index.php",type:"POST",data {type:"populate",index:2,value:"option1"},dataType:"json",
success: function(data) {
// data (json) returned from server so populate other selection boxes with that..
// in this example 'data' is an array, coming directly from server (see below the .php)
$("#other_select")[0].selectedIndex = 0;
for(var x in data) {
$("#other_select")[0].options[x] = new Option(data[x]);
}
}
})
in your .php i assume you get a list (etc. database) to populate the other selection list (in client). This code could looks like:
if (isset($_POST["type"]) && $_POST["type"]=="populate") {
echo json_encode(array("option1","option2","option3"));
exit(1);
}
$('#searrec').submit(function () {
//do some form submit work here
return false;
});
You'll have to use an AJAX call to populate the other select boxes based on whatever you've selected in the first one without reloading the page.
I suggest you take a look at jQuery's AJAX functionality. Read up on $.ajax and $.post - with them you could submit the value that you've selected in the first listbox to a PHP script and then based on that value return and populate the other select boxes.
Use AJAX to update the other selects without refreshing the page. Use jQuery to make AJAX easy.
This question will help:
Change the selected value of a drop-down list with jQuery
$('#searrec').submit(function(e){
e.preventDefault();
});
You should delete event onchange="this.form.submit(); from combobox
And use ajax with jquery:
$("#searrec").onchange(function() {
$.ajax({
url:"",
success:function(response){
alert("success");
}
});
});
Guys its fixed.
Plz have a look at http://giftideasitems.com/.
See gift finder box and see how it works.
I used iframe and embedded the forms, drop down coding there. thats it.
Even I used onchange="this.form.submit()" and page doesnot referesh, actually page refresh .... but not the main page, only the iframe is refreshing which is fine. this is exactly what i wanted.
<div id="gift-finder">
<div class="gift-finder-form">
<iframe name="inlineframe" src="code.php" frameborder="0"
scrolling="auto" width="200" height="180"
marginwidth="0" marginheight="0" id="gift-iframe">
</iframe>
</div>
This is my iframe code and see src, i used code.php; so all code is in separate place.
Though I had to modify some css, but anyways this is fine.
Thanks everyone who contributed yesterday.