Gopal Joshi
Gopal Joshi

Reputation: 2358

How to retrieve records from mysql table using select option ONCHANGE event

I have one table like

mst_city

ID    City         Country
1     Pune         India
2     london       UK
3     California   US
4     Dubai        UAE

PHP

<select name="city_select">
<?php
$result = mysql_query("SELECT * FROM `mst_city`");
while($row = mysql_fetch_array($result))
        {                                                      
        echo "<option value= ". $row['id'] ." selected='selected'> " . $row['city'] ." </option>";
?>
</select>
<input type="date" name="country" class="text" value=""/>

How can i change country name in textbox when change city in select option.

Upvotes: 0

Views: 5392

Answers (2)

Yair Nevet
Yair Nevet

Reputation: 13013

Handle the change event in jQuery by performing an AJAX request upon each city selection change:

$('input[name=city_select]').on('change', function() {
     //Do the AJAX request for country here, like:
     $.get("getCountryByCity.php?cityId="+$(this).val(), function( data ) {
          //Set the retrieved country:
          $('input[name=country]').val(data);
});

In addition, your PHP code should be like this for querying the counrty from mysql by the city-id:

<?php
    $countryQuery = mysql_query("SELECT Country FROM `mst_city` WHERE ID = "+ $_GET['cityId']);
    $row = mysql_fetch_array($countryQuery);
    echo $row[0];
?>

Upvotes: 4

Sunil Verma
Sunil Verma

Reputation: 2500

one you can create a javascript array to do so, and then use it on change property.

Second you can use AJAX to find country name on run time and feed it to the input box.

Upvotes: 3

Related Questions