Hey,

I need a 2-level drop down selection for the state-city selection where the code gets the values of these dropdowns from the mysql database(since i'm using php).
After the selection of the state the code should display the cities belonging to that particular state.

Could you please provide me a simple Ajax and PHP code for this.


Thanks in advance
Akshay

A jQuery solution can be found here: http://www.pritaeas.net/demos/jq-dropdown/

cities.php is as simple as this:

<?php
  include 'defines.inc.php'; // my connection settings
  $state = isset($_GET['state']) ? $_GET['state'] : 0;
  $cities = array ();
  if ($state > 0) {
    $link = @mysql_connect(HOST, USER, PASS);
    @mysql_select_db(DATABASE);
    $query = "SELECT id, name FROM cities WHERE state = $state ORDER BY name";
    $result = @mysql_query($query);
    if ($result) {
      while ($record = @mysql_fetch_assoc($result))
        $cities[] = array ('id' => $record['id'], 'name' => $record['name']);
    }
    @mysql_close($link);
  }
  echo json_encode($cities);
?>

Am sure you can figure out the rest.

Hey pritaeas,

Could you please give me the complete code of this. I am a bit new to jquery and ajax so am finding it hard to understand your code.

The javascript/jquery code can be downloaded using your browser. Just use 'view source'.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.