I am having a problem with my PHP script. I have been working and researching this problem for days without any resolution. I have a dependent drop-down. When a user selects Country, State, and City from select/option dependent drop-downs my script will only save the ID numbers associated with the Country, State, and City. The script sets the IDs to values in order to access each other. However, I would like the database to ultimately save the actual names of the Countries, States, and Cities and not the ID numbers.
I am also using localstorage to save these names in case of a page refresh. In localstorage the State and City work correctly by saving the actual names. However, once again, the Country saves only an ID here as well.
I am learning PHP as a beginner programmer, so I am not well versed as of yet. If anybody can help me by pointing out my errors and how to fix them I would be very grateful. I will paste my code here.
Thank you all in advance.
<li>
<fieldset>
<div>
<select id="country" class="country" name="country" title="select country">
<?php include("../php_includes/countryAjaxData.php"); ?>
</select>
</div>
<div>
<select id="state" class="state" name="state" title="select your state">
<option value="" selected="selected">Select State</option>
</select>
</div>
<div>
<select id="cityā class="city>
<option value="" selected="selected">Select City</option>
</select>
</div>
</fieldset>
</li>
<script>
//Load Country Data into dropdown menus
window.load=$(document).ready(function() {
var countryName = $(this).val();
$.ajax ({
type: "POST",
url: "../php_includes/countryAjaxData.php",
data: 'country='+countryName,
//dataType: 'json', // Required to read response as JSON
success: function(html) {
$('.country').html(html);
$('.country').each(function(i) {
var thisSelection = $(this);
var thisId = thisSelection.attr('id');
var storageId = 'country-' + thisId;
var storedInfo = localStorage.getItem(storageId);
if( storedInfo ) {
var rememberedOptions = storedInfo.split(',');
thisSelection.val( rememberedOptions );
}
thisSelection.on('change', function(e) {
var selectedOptions = [];
thisSelection.find('option:selected').each(function(i) {
var thisOption = $(this);
selectedOptions.push(thisOption.val());
});
localStorage.setItem(storageId, selectedOptions.join(','));
});
});
}
});
});
</script>
<script>
//On country dropdown change trigger this
$('.country').on('change', function () {
var countryId = $(this).val();
var state_select = $(this).closest('fieldset').find('.state');
var city_select = $(this).closest('fieldset').find('.city');
if (countryId) {
$.ajax( {
type: 'POST',
dataType: 'JSON', // Required to read response as JSON
url: '../php_includes/ajaxData.php',
data: {
country_id: countryId
},
success: function (r) {
//console.log('States', r);
if (r.status) {
r.data.map(function (state) {
$(state_select).append(`<option value="${state.id}" name="${state.name}">${state.name}</option>`);
$('.state').each(function(r) {
var stateList = $(state);
var thisSelection = $(this);
var thisId = thisSelection.attr('id');
var storageId = 'state-' + thisId;
var storedInfo = JSON.parse(localStorage.getItem(storageId));
thisSelection.change(function(i) {
var selectedOptions = [];
thisSelection.find('option:selected').map(function(i) {
var thisOption = $(this);
selectedOptions.push(thisOption.val());
localStorage.setItem(storageId, JSON.stringify(thisOption.text()));
})
})
})
})
} else {
//$('.error').html('No States);
$(state_select).html('<option class="nostate" value="no_states " name="state_unavail" selected="selected">No States</option>')
var select_state = $('#countryfieldset').find('[name=state_unavail]');
$(city_select).html('<option class="nocity" value="no_city" name="city_unavail" selected="selected">No Cities</option>')
var select_city = $('#countryfieldset').find('[name=city_unavail]');
}
}
})
};
});
// On state dropdown change trigger this
$('.state').on('change', function () {
var stateId = $(this).val();
var city_select = $(this).closest('fieldset').find('.city');
if (stateId) {
$.ajax( {
type: 'POST',
dataType: 'json', // Required to read response as JSON
url: '../php_includes/ajaxData.php',
data: {
state_id: stateId
},
success: function (r) {
if (r.status) {
r.data.map(function (city) {
$(city_select).append(`<option value="${city.id}">${city.name}</option>`);
$('.city').each(function(r) {
var cityList = $(city);
var thisSelection = $(this);
var thisId = thisSelection.attr('id');
var storageId = 'city-' + thisId;
var storedInfo = JSON.parse(localStorage.getItem(storageId));
thisSelection.change(function(i) {
var selectedOptions = [];
thisSelection.find('option:selected').map(function(i) {
var thisOption = $(this);
selectedOptions.push(thisOption.val());
localStorage.setItem(storageId, JSON.stringify(thisOption.text()));
})
})
})
})
} else {
//$('.error').html('No Cities Available.');
$(city_select).html('<option class="nocity" value="no_city_available" name="city_unavail" selected="selected">No Cities</option>');
var select_city = $('#countryfieldset').find('[name=city_unavail]');
}
}
})
};
});
});
</script>
<script>
$sql = 'SELECT `id`, `name` FROM `countries` ORDER BY `name` ASC' ;
$query = $database_connection_here ->query($sql);
//if there is at least one country display message
if($query->rowCount() > 0) {
echo '<option value="">Select Country</option>';
while($country = $query->fetch(PDO::FETCH_ASSOC)) {
echo ('<option value="' . $country['id'] . '"name="' . $country['name'] . '" >'.$country['name'] . '</option>'); //select country id and show it's name from country table
}
} else {
echo '<option value="">Data Not Available</option>';
}
</script>
<script>
$resp = array(
'status' => false,
'data' => []
);
/*-----------------------------------
| Grab States based on Country
-----------------------------------*/
if (isset($_POST["country_id"]) && !empty($_POST["country_id"])) {
$sql = "SELECT `id`, `name` FROM `states` WHERE `country_id` = " . $_POST['country_id'] . " ORDER BY `name` ASC";
$query = $database_connection_here ->query($sql);
if ($query->rowCount() > 0) {
$resp['status'] = true;
while ($state = $query->fetch(PDO::FETCH_ASSOC)) {
$resp['data'][] = $state;
}
}
echo json_encode($resp);
}
/*-----------------------------------
| Grab Cities based on State
-----------------------------------*/
if (isset($_POST["state_id"]) && !empty($_POST["state_id"])) {
$sql = "SELECT `id`, `name` FROM `cities` WHERE `state_id` = " . $_POST['state_id'] . " ORDER BY `name` ASC";
$query = $database_connection_here ->query($sql);
if ($query->rowCount() > 0) {
$resp['status'] = true;
while ($city = $query->fetch(PDO::FETCH_ASSOC)) {
$resp['data'][] = $city;
}
}
echo json_encode($resp);
}
</script>