0

I have an html form where the countries in the drop down are coming from a database. If the user selects any country, then the city drop down will appear based on selected country.

If user wrongly inputs any field of the form (there are other fields in this form) then country drop down will remember which country the user has initially selected, but clears the city, resetting it to --Select City--. I'm trying to select the city name but I can't. Any idea?

Html form here:

<tr>
    <td>PAYS <span style="color: #FF0000;">*</span></td>
    <td>
<select name="country" class="country">
<option value="">Select</option>

<?php
    $sql=mysql_query("select * from country");
    while($row=mysql_fetch_array($sql))
    {
        $id=$row['Code'];
        $data=$row['Name']; 
        $data = mb_convert_encoding($data, 'UTF-8');
    if($id == $_POST['country'])
    {
        $sel = 'selected="selected"';
    }
    else
    {
        $sel = "";
    }

        echo '<option value="'.$id.'"' . $sel . '>'.$data.'</option>';
    }
?>
</select>   
</td>
</tr>   

<tr>
<td>City</td>
    <td>
    <select class="city" name="city">
<option selected="selected" value="">--Select City--</option>
</select>   
    </td>
</tr>

Ajax Code here:

<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;

$.ajax({
    type: "POST",
    url: "ajax_city.php",
    data: dataString,
    cache: false,
    success: function(html)
{
$(".city").html(html);
} 
});

});
});
</script>

ajax_city.php here

<?php
require_once("toplevel/content/database/databd.php");
if($_POST['id'])
{
    $id=$_POST['id'];
    $sql=mysql_query("select Name from cities WHERE CountryCode ='$id'");
    while($row=mysql_fetch_array($sql))
    {
        $id=$row['Code'];
        $data=$row['Name'];
    if($_POST['city'] == $data)
    {
    $sel = 'selected = "selected"'; 
    }
    else
    {
    $sel = " ";
    }
     echo '<option value="'.$data.'" ' .$sel . ' >'.$data.'</option>';
    } 
}
?>
Chubas
  • 17,823
  • 4
  • 48
  • 48
Babu Ahmed
  • 121
  • 1
  • 3
  • 8
  • Consider validating input client side and you will catch the invalid field before posting to server, thus no need to reload the page. Having that said, you might still want to keep the server validation to prevent get/post manipulation. – J.G.Sebring Mar 23 '13 at 09:47

3 Answers3

1

Because, in your AJAX request, you are defining the data as POST, and you are providing GET data style where a JSON map is expected. In that case, your PHP script will never received the expected ID, and nothing will happened.

Try like this :

$(document).ready(function () {
    $(".country").change(function () {
        var myId = $(this).val();

        $.ajax({
            type: "POST",
            url: "ajax_city.php",
            data:{id : myId},
            cache: false,
            success: function (html) {
                $(".city").html(html);
            },
            error : function(jqXHR, textStatus, errorThrown) {
                alert('An error occurred!')
            }
        });

    });
});
sdespont
  • 13,915
  • 9
  • 56
  • 97
0

Make sure that posted id is valid. You can use firebug on Mozilla to see the same, if id is right then-

Use append() function instead of html() in success function-

$(document).ready(function () {
    $(".country").change(function () {
        var myId = $(this).val();

        $.ajax({
            type: "POST",
            url: "ajax_city.php",
            data:{id : myId},
            cache: false,
            success: function (html) {
                $(".city").append(html);
            }
        });

    });
});
Prateek Shukla
  • 593
  • 2
  • 7
  • 27
0

As I mentioned as a comment, the quick fix is to validate client side to prevent the form from posting if it isn't valid. That way you will not loose the city names you retrieved from server. This is not fool-proof but will probably in most cases fail more gently than what you got right now.

You can also check the country selections on page load. If the first option is selected you do nothing, otherwise call the ajax you already uses to populate city dropdown. Put it in a separate function to avoid code duplication.

$(document).ready(function() {
    // call ajax if country is selected
    if (document.getElementById('countries').selectedIndex != 0) {
        // call you ajax to populate cities
    }

This assumes you add id="countries" to the country select dropdown.

I strongly recommend you to add id on the dropdowns. Relaying on unique class names and calling $('.city').html() might accidentally give you some funny results if you happen to add the class name to other elements as well.

J.G.Sebring
  • 5,934
  • 1
  • 31
  • 42