Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
Ajax State, City Drop Down Menu

I'm trying to create a program that when you select a state from the drop down menu, it will display the list of cities for that state in another drop down menu that you can select from. After you choose your city and state, you type in an address, hit submit, and it will display the full address on a new php file.

My issue at the moment is I can get the states displayed, but when the state is selected, it is not giving me the list of options for that city in the second drop down menu. Any help is appreciated, thanks!

You can view the behavior at this link

select.php

<head>
<link rel="stylesheet" type="text/css" href="select_style.css">
<script type="text/javascript" src="js/jquery.js"></script>
<!DOCTYPE html>
<form action = "display.php">
<script type="text/javascript">


function fetch_select(val)
{
 $.ajax({
 type: 'post',
 url: 'fetch.php',
 data: {
  get_option:val
 },
 success: function (response) {
  document.getElementById("new_select").innerHTML=response; 
 }
 });
}

</script>

</head>
<body>
<p id="heading">Address Generator</p>
<center>
<div id="select_box">
 <select onchange="fetch_select(this.value);">
  <option>Select state</option>


  <?php
  include (  "accounts.php"     ) ;
( $dbh = mysql_connect ( $hostname, $username, $password ) )
            or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db( $project ); 

  $select=mysql_query("select state from zipcodes group by state");
  while($row=mysql_fetch_array($select))
  {
   echo "<option>".$row['state']."</option>";
  }
 ?>
 </select>

 <select id="new_select">
 </select>

<div id='2'> </div>
<br><br>
<input type = text name="address">Address
<br><br>
<input type = submit>

</form>

fetch.php

<?php
include(accounts.php);
if(isset($_POST['get_option']))
{
 ( $dbh = mysql_connect ( $hostname, $username, $password ) )
            or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db( $project );


 $state = $_POST['get_option'];
 $find=mysql_query("select city from zipcodes where state='$state'");
 while($row=mysql_fetch_array($find))
 {
  echo "<option>".$row['city']."</option>";
 }
 exit;
}
?>
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

1)First of all your state option's value attribute is missing

echo "<option value='".$row["state"]."'>".$row["state"]."</option>";

2)Include(accounts.php); accounts.php should be enclosed by double quotes

3) And city option's value attribute is missing

echo "<option value='".$row["city"]."'>".$row["city"]."</option>";

4) Instead of echoing each time concatenate and echo finally like this

$options="";
while($row=mysql_fetch_array($find))
 {
     $options.= "<option value='".$row["city"]."' >".$row["city"]."</option>";
  }

 echo $options;

Warning!!!

Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.

over 4 years ago · Santiago Trujillo Report

0

I've modified your code a little. Tried to do it the elegant way. You had wrote too much of superfluous code. You didn't need a <form> element to perform the asked operation. Anyway below is the modified code.

<!DOCTYPE html>
<head>
    <title>Address Generator</title>
</head>
<body>
    <p id="heading">Address Generator</p>
    <center>
    <!-- <div id="select_box"> -->
    <select name="select_box" id="select_box">

        <?php
            include (  "accounts.php"     ) ;
            ( $dbh = mysql_connect ( $hostname, $username, $password ) ) or die ( "Unable to connect to MySQL database" );
            print "Connected to MySQL<br>";
            mysql_select_db( $project ); 
            $select=mysql_query("select state from zipcodes group by state");
            while($row=mysql_fetch_array($select))
            {
                echo "<option>".$row['state']."</option>";
            }
         ?>            
    </select>
    <select id="new_select">

    </select>
    <div id='2'> </div>
    <br><br>
    <input type = text name="address">Address
    <br><br>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#select_box').on('change', function() {
                var state = $(this).val();
                $.ajax({
                    url: 'fetch.php',
                    type: 'POST',
                    data: {state: state},
                    success: function(response)
                    {
                        var response = JSON.parse(response);
                        $('#new_select').find('option').remove();
                        var option = '';
                        $.each(response.cities, function(key, val) {
                          option = option + "<option value='" + val + "'>" + val + "</option>";
                        });
                          $('#new_select').append(option);
                    }
                });
            });
        });
    </script>
</body>
  1. I've added Jquery before the end of </body> tag. This doesn't hinder your current code execution. However you could always preload it but that tactic is for later.
  2. Since you didn't need any <form> element so I've completely removed it. You can always add it according to your convenience.
  3. I'm running a loop on the cities array of the object response that I'm getting from fetch.php.
  4. parsing the JSON data using JSON.parse() function.
  5. You'll need to json_encode your json variable which will store the corresponding citites data.

I hope this helps. Any further queries are welcome too.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!