I have a db table of all postcodes in the UK and want to create functionality to filter down into local locations to decrease load times of the page. The issue I am having is that I am a bit out of practice with JQuery and there seems to be an issue where selecting the country is not being picked up by the JQuery.
Here is the HTML/PHP for the select:
<label for="country_select">
Select Country
</label>
<select id="country_select" name="country_select" class="form-control search-select">
<option value=""> </option>
<?PHP
if ($result = mysqli_query($link, "SELECT DISTINCT(`country`) as countrylist FROM `postcodes`")) {
while($member = mysqli_fetch_assoc($result)) {
$country=$member['countrylist'];
?>
<option value="<?PHP echo $country; ?>"><?PHP echo $country; ?></option>
<?PHP
}
}
?>
</select>
Here is the PHP to check for the post and create a mysql statment to then create another drop down for cities. I am wondering if the issue lies here, i added an echo to see if it appears when the option has been changed, but nothing is appearing.
<?PHP
if (isset($_POST['CountryID'])) {
$country_query = $_POST['CountryID'];
$statement = " AND `country` = '".$country_query."' ";
echo $statement;
}
?>
And here is the jquery:
$(document).ready(function(){
$("#country_select").change(function () {
var country_name = $("#country_select").val();
jQuery.ajax({
type: "POST",
data: {CountryID: country_name},
success: function(data){
if(data.success == true){
alert('success');
}
}
});
});
});
I am unsure where I am going wrong as it has been a while since I have coded. I have looked around at others' issues with no luck. Any help would be greatly appreciated.
My Answer:
One issue in your code is that you are not returning any data from the PHP script back to the jQuery AJAX call. You need to echo out a response in your PHP script so that the success function in your AJAX call can handle it.
Here is an updated version of your PHP script:
php
if (isset($_POST['CountryID'])) {
$country_query = $_POST['CountryID'];
$statement = " AND `country` = '".$country_query."' ";
echo json_encode(array('success' => true, 'statement' => $statement));
}
?>
And in your jQuery AJAX call, you can access the data returned from the PHP script like this:
javascript
$(document).ready(function(){
$("#country_select").change(function () {
var country_name = $("#country_select").val();
jQuery.ajax({
type: "POST",
data: {CountryID: country_name},
success: function(data){
if(data.success == true){
alert('success');
console.log(data.statement); // This will log the statement returned from PHP
}
}
});
});
});
By making these changes, you should now be able to see the statement echoed from the PHP script in the console when the country select is changed. This will help you debug and see if the AJAX call is working correctly.
Rate this post
4 of 5 based on 2769 votesComments