AJAX with jQuery in WordPress: AJAX call not passing property value to PHP function

So I’m trying to build something that should be incredibly simple — A form that has State and Area, and when you select a state, it populates the list of areas. My form has two menus, #select-region (state), and #select-area. Here’s my jQuery code that is included in a .js file:

jQuery(document).ready(function() {
    jQuery("#select-region").change(function(){
    //alert(jQuery("#select-region").val());
    regionID = jQuery("#select-region").val();
    jQuery.ajax({
            type: 'POST',
            url: 'http://dev.sitename.com/wp-admin/admin-ajax.php',
            data: {
                action: 'get_area_menu',
                region_id: regionID,
            },
            success: function(data, textStatus, XMLHttpRequest){
                jQuery("#select-area").html('');
                jQuery("#select-area").append(data);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                alert(errorThrown);
            }
        });
     });
});

The ‘get_area_menu()’ function is in my functions.php file. Here’s the code:

Read More
function get_area_menu($region_id){
    $areas = get_areas($region_id);

    $menu_output = "<option>" . count($areas) . "</option>";
    foreach($areas as $area) {
        $menu_output = $menu_output . "<option value=" . $area['area_id'] . ">" . $area['name'] . "</option>";
    }
    die($menu_output);
}
add_action('wp_ajax_get_area_menu', 'get_area_menu');
add_action('wp_ajax_nopriv_get_area_menu', 'get_area_menu');

`

Now, I’ve verified that the ‘get_areas()’ function that is called in the above function is working properly when a region_id is passed to it, but for some reason the region_id variable is not being passed into get_area_menu() from the AJAX call. FWIW, I have enqueued the script and localized it (although I still have no idea what that actually means) with this code near the top of functions.php:

wp_enqueue_script('jquery');
wp_enqueue_script('sitename', get_template_directory_uri() . '/scripts/sitename.js');
wp_localize_script( 'sitename', get_template_directory_uri() . '/scripts/sitename.js', $params);

Guys, I’m at my wit’s end. What am I missing?

Related posts

Leave a Reply

1 comment

  1. The only thing I can see is in your get_area_menu function change this line

    $areas = get_areas(isset($_POST['region_id']) ? $_POST['region_id'] : $region_id);