0
votes

I have a PHP code that retrieve data from MYSQL database and includes these retrieved data into a dropdown list where 2 dropdown list exist, the user select from the first one and based on his selection the second one will display the related data.

  • tbl_country:
    • country_id
    • country_name
  • tbl_state:
    • state_id
    • state_name
    • country_id

can anyone tell me where the error in the code?

code 1:

<?php

function load_country(){
  $connect = mysqli_connect("localhost","****","***","test");
  $output = '';
  $sql = "select * from tbl_country";
  $result = mysqli_query($connect,$sql);
 // var_dump($result);
   while ($row = mysqli_fetch_array($result)) {
     $output.='<option value="'.$row["country_id"].'">'.$row["country_name"].'</option>';   
   }
   return $output;

}
?>

<html>
<head>
    <title>dropdown test</title>
    <script  src="jquery.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
       $('#country').change(function(){
         var country_id = $(this).val();
         $.ajax({
            url:"dropdown_fetch.php",
            method:"POST",
            data:{countryId:country_id},
            datatype:"text",
            success:function(data){
                $('#state').html(data);
            }

         });
       });

    });

</script>
</head>
<body>
     <p>select owner 
     <select name="country" id="country">
     <option value="">Select country</option>
     <?php echo load_country(); ?>
     </select></p>
     <p>select state 
     <select name="state" id="state">
     <option value="">Select state</option>
     </select></p>

</body>
</html>

code 2:

<?php
$connect= mysqli_connect("localhost","****","****","test");
$output = '';
$sql = "select * from state where country_id = '".$_POST["countryId"]."' ORDER BY country_name";
$result = mysqli_query($connect,$sql);
//var_dump($_POST["ownerID"]);
$output='<option value="">Select state</option>';
while ($row = mysqli_fetch_array($result) {
    $output.='<option value="'.$row["state_id"].'">'.$row["state_name"].'</option>';
}
echo $output;

?>
1
what error are you getting? can you post it?landrykapela
@kampangala there is no error but the second dropdown just do nothing still display select stateAmin 3amin
Try and inspect the XHR object you sent and the response (request and response headers) e.g. via developer console. It is a nice way to start the debugging.Damilola Olowookere
@OlowookereEmmanuel in the console this error is displayed : ReferenceError: $ is not defined[Learn More] dropdown.php:7:2 <anonymous> 127.0.0.1/dropdown.php:7:2Amin 3amin
Then your ajax script is not loaded. Any error 404 in the network tab of the console?Damilola Olowookere

1 Answers

0
votes

Here is a syntax error in your while loop. Fix the line in code 2:

while ($row = mysqli_fetch_array($result)

to

while ($row = mysqli_fetch_array($result))