Populate list of options with Ajax - Replacing Prototype
HI, I have a problem with a jQuery code.
Actually, I want to migrate from Propotype due to conflicts with other jQuery scripts.
I need display a list of options in a select from a previously option selected in another select.
I've tried several ways, but without success.
I added two fields to the users profile: City and Neighborhood. So, a form in the frontend to be able to search for users by city and neighborhood (of each city).
Here's my code:
The file
neighborhoodAjax.php
- <?php
- /*
- This file is used to search the neighborhoods of the city selected in the first select and populate the list of neighborhoods of that city.
- */
- global $wpdb; // here's used for connect in DB and get the prefix of table
- if($_POST['meta_value']){
- $city_selected = $_POST['meta_value'];
- $neighborhood = "SELECT DISTINCT meta_value FROM $wpdb->usermeta WHERE meta_key = 'neighborhood_of_user' AND user_id IN (SELECT DISTINCT user_id FROM $wpdb->usermeta WHERE meta_key = 'city_of_user' AND meta_value = '".$city_selected."')";
- $neighborhood = sanitize_text_field($neighborhood);
- $neighborhood = mysql_query($neighborhood); ?>
- <option value="" selected="selected">-- Select a Neighborhood --</option>
- <?php while($neighborhood = mysql_fetch_array($neighborhood)){ ?>
- <option value="<?php echo $neighborhood['meta_value'] ?>" <?php if($_POST['select_neighborhood'] == $neighborhood['meta_value']) {?> selected="selected" <?Php } ?>> <?php echo $neighborhood['meta_value']?> </option>
- <?php }//Close the While
- }//Close the if
- ?>
The Script:
- <script type="text/javascript">
- $(function() {
- $("#city").bind("change", function() { // #city is ID of select
- var meta_value = $("#city").val();
- $.ajax({
- url: "neighborhoodAjax.php",
- type: "POST",
- data: {id : meta_value},
- dataType: "html"
- });
- });
- });
- </script>
The code will run in WordPress website, what I would like to know is where the error is. :(
Can anyone help me?
I am grateful.