0

I have a database table name country & states I am trying to call states when country is selected every sates has associated country column name XX like for Pakistan PK, for United States of America US and so on my code examples are below to find a solution.

Country Select Box

<select name="country" id="country">
<option value="-1">Select Country</option>
<?php
    $query = $mysqli->query("SELECT * FROM `country`");
    while ( $row = mysqli_fetch_assoc($query) ) {
        echo '<option value="'.$row['country_code'].'">';
            echo $row['country_name'];
        echo '</option>';
    }
?>

State Select Box

<select name="country" id="states">
<option value="-1">Select State</option>
</select>

Ajax Call

$(document).ready(function(){
    $('#country').on('change',function(){
        var countryCode = $(this).val();
        if(countryCode){
            $.ajax({
                type: "POST",
                url: 'getStates.php',
                data: {countryCode:country_code},
                success:function(data){
                    $("#states").html(data);
                }
            });
        }
    });
});

I have the separate file where I am fetching states with ajax

<?php include_once("inc/config.php");?>
<option value="-1">Select State</option>
<?php
    $query = $mysqli->query("SELECT * FROM `state` WHERE `country_code` = '".$_POST['country_code']."' ");
    while( $row = mysqli_fetch_array($query) ){
        echo '<option value="';
            $row['state_id'];
        echo '">';
            echo $row['state_name'];
        echo '</option>';
    }
?>
<option value="Other">Other</option>

Note: Database connection is ok because when I insert 'PK' instead of '".$_POST['country_code']."' in getStates.php file it works fine and when I insert console.log() in ajax success:function(data){console.log()} it shows related value of country but I think I am doing some mistake somewhere in ajax code.

I also get an undefined variable error when I insert $_POST['country_code'] or $_POST['countryCode'] in getStates.php file.

I am sure there is something wrong in ajax call

shaz3e
  • 316
  • 2
  • 14
  • You might want to also review https://stackoverflow.com/questions/5918144/how-can-i-use-json-data-to-populate-the-options-of-a-select-box if I'd answered I would have included this – Barry Aug 26 '18 at 15:50

1 Answers1

1

You're trying to send country_code as a value. But you haven't declared the variable. Try:

data: {'countryCode':countryCode},

Also: you might want to add some security checks before using a variable posted by your user in a query. Have a look: https://en.wikipedia.org/wiki/SQL_injection

  • NOw I am getting ( ! ) Notice: Undefined index: countryCode in path/to/getStates.php on line X I am using $_POST['CountryCode'] in getStates.php file – shaz3e Aug 26 '18 at 21:27
  • Just found a solution https://www.w3schools.com/php/php_ajax_database.asp now everything is working fine. – shaz3e Aug 27 '18 at 15:00