0

I have a HTML form, and when i fill in a zipcode, i want the city field to be automatically updated to the city that belongs with that zipcode.

Here's my form:

<form method="post" action="">
    <input type="text" name="zipcode" id="zipcode">
    <input type="text" name="city" id="city">
</form>

Here is my ajax:

$('#zipcode').keyup(function () {
    var el = $(this);
    if (el.val().length == 4) {
        $.ajax({
            url: 'get_city.php',
            cache: false,
            type: "GET",
            data: "zipcode=" + el.val(),
            success: function (data) {
                $('#city').val(data);
            }
        })
    }
});

And here is the PHP

$db = mysql_connect('localhost', 'root', '');
mysql_select_db('testbox_new', $db);

$sql = 'select * from cities where zipcode = "'.$_GET['zipcode'].'"';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($sql)) {
    return $row['city_name'];
}

Anyone who knows why this isn't working?

Thx :)

MrSkippy
  • 348
  • 4
  • 17
  • Check console for any javascript errors – 웃웃웃웃웃 Aug 28 '13 at 10:16
  • You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Aug 28 '13 at 10:20
  • you should study about passing data in ajax call , check the answer below – Deepanshu Goyal Aug 28 '13 at 10:20

2 Answers2

3

You are returning the value you find instead of echoing it.

Try

echo $row['city_name'];

instead of

return $row['city_name'];
Atif
  • 10,623
  • 20
  • 63
  • 96
slash197
  • 9,028
  • 6
  • 41
  • 70
1

The data sending in your ajax is wrong.Try this one.

 $.ajax({
     url: 'get_city.php',
     cache: false,
     type: "GET",
     data: {"zipcode": el.val()},
     success: function(data) {
         $('#city').val(data);
     } 
 });

Also echo the value in your php file.Because return will not give you the response for ajax

$db = mysql_connect('localhost', 'root', '');
mysql_select_db('testbox_new', $db);
$sql = 'select * from cities where zipcode = "'.$_GET['zipcode'].'"';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($sql)) {
    echo $row['city_name'];
}
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91