简体   繁体   中英

Populating second dropdown on the same page

I am trying to populate a second dropdown based on first on the same page without having to call any external PHP script. I have been testing ajax but it is not working, it has to call another PHP script externally.

I have states, so when a state is clicked it populates the second dropdown with the locality for that state from the db the first dropdown is working properly but the second isn't working. This is my code, been trying ajax nothing works.

I want to echo the value from the db on the same page without calling any external PHP script. How can I pass the first dropdown value to the second dropdown PHP code below for query to the db? Not calling another PHP file externally, all on the same page?

       //first dropdown//
<select name="state" class="select" >
     <option selected>State</option>
        <?php 
  $u =  "SELECT * FROM state_id";
  $sql = mysqli_query($con, $u);
  while ( $row = mysqli_fetch_assoc($sql)) 
  {
 echo '<option>'.$row['name'].'</option>';
 }
 ?>

        </select>
        </div>
      </div>
          <div class="col-md-2">
        <div class="aa-single-advance-search">
           <!-- second dropdown on the same page -->

              <select name="locality" class="select2">
              <option selected>Location</option>
                                 <?php 
                                //local area is the table i am getting localities based on state value in the first select menu//
      $u =  "SELECT name FROM local_area WHERE state_id='$id'";
        $sql = mysqli_query($con, $u);
         while ( $row = mysqli_fetch_assoc($sql)) 
      {
         echo '<option>'.$row['name'].'</option>';
     }
      ?>
              </select>

A common mistake (perhaps not one you are encountering, but fwiw) is to think the PHP code can somehow run the AJAX. Not true. Once the page is rendered, PHP cannot run. That's where javascript comes in, and that's why AJAX is started in js/jQuery.

Note that jQuery is a library that you reference/load on your page. Not only is it 30% less typing (that fact alone is a good enough reason to use it), but it is also automatically cross-browser. More importantly, jQuery makes AJAX easy.

Study this (working) example. Perhaps even reproduce the example on your server and monkey around with it a bit. Turn the example into your own solution.

Populate dropdown B based on selection in dropdown A

我几乎没有做任何工作,但确实有效,但令我感到困惑的是外部php脚本和第二个下拉列表之间的关系。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM