I have two select box and the second select box value is dependent on the first select box. So basically what I am trying to do is that after a user makes a selection on the first select box, it will then store this value of the first select box as a variable. Then it will query my database to populate the second select box, based on the first selected value. Question is, how do I pass in the var I have in the first select box to PHP? I've read other post and people said it's impossible, but if it is then how do people do this? AJAX?
-
1Obviously it is not impossible. (Who writes such nonsense? Do you have a link?)Tomalak– Tomalak2011-09-10 18:03:39 +00:00Commented Sep 10, 2011 at 18:03
-
Have you book an air ticket before? I think most of the booking site is doing this -- upon select a country, reload the second list with cities. Is this what you looking for?ajreal– ajreal2011-09-10 18:06:56 +00:00Commented Sep 10, 2011 at 18:06
-
You'll need to use Ajax for that.Sahil Muthoo– Sahil Muthoo2011-09-10 18:07:07 +00:00Commented Sep 10, 2011 at 18:07
-
yes, that's what I am looking for.. but possibly I wanted to use PHP if possible.. if not can someone show me an AJAX way to do this with MySQLaherlambang– aherlambang2011-09-10 18:08:12 +00:00Commented Sep 10, 2011 at 18:08
7 Answers
I assume that you have a Country/City dropdowns, You can do it in two ways, the good AJAX way and the bad way (refresh page on change), I'm gonna describe the good way in jQuery, or at least what I see it good.
this is the client-side (i.e. client) code:
<select id="country">
<option value="1">Canada</option>
<option value="2">UK</option>
</select>
<select id="city" disabled="disabled"></select>
<script type="text/javascript">
$('#country').change(function(){
$('#city').load('/ajax-city.php', {id: $(this).val()});
});
</script>
This is the ajax-city.php code (server):
<?php
$countryId = $_REQUEST['id'];
$cities = array(); // Get it from db, using mysql_query or anything you want to use
foreach($cities as $city) {
echo "<option id=\"{$city['id']}\">{$city['name']}</option>";
}
PS. you would need to include jQuery in your html code, and of course put the two files in the same directory (or change the $.load path).
This particular code is not tested, I've just written it. But it usually works fine to me this way.
Comments
If I see correct you're using Jquery. So you can do this like this:
$('#idOfSelectBox1').change(function(){
jQuery.ajax({
type: "GET",
url:"yourdomain.com/script.php",
data:"selectBox:'"+$('#idOfSelectBox1').val()+"'",
success:function(result){
//do smth with the returned data
}
});
});
in the script.php do your magic and echo what you want to pass back to js