How to declare a JS variable in an AJAX call

The right way is to post the data back to the WordPress admin ajax url then in your PHP function access them using the $_POST variables.

Example jQuery function that passed a category id back to wordpress:

function cat_edit_get() {
    jQuery( "#loading-animation").show();
    var catID = jQuery("#cat :selected").val();
    var text = jQuery("#cat :selected").text();
    jQuery('#replace').html(text);

    jQuery.ajax({
        type: 'POST',
        url: ajaxurl,
        data: {"action": "cat-editor-get", cat: catID },
        success: function(response) {
            jQuery("#the-list").html(response);
            jQuery("#loading-animation").hide();
            return false;

        }
    });

}

Then you can access the variables in WordPress by hooking into the wp_ajax action. Here I’m only passing category id chosen from a drop down select:

add_action ( 'wp_ajax_cat-editor-get', 'cat_editor_get' );
    function cat_editor_get () {
        $cat_id = $_POST[ 'cat' ];
        $preview_cats = get_post_meta ( 82799, '_' . $cat_id . 'saved', true );
        $item_order = $preview_cats[ 'cat_order' ];
        $post_ids = explode ( ",", $item_order, 30 );
        global $post;
        if ( count ( $post_ids ) < 5 ) {
            $args = array (
                'category_id' => $cat_id,
                'length' => 30,

            );

            $post_ids = wndsq_get_post_ids ( $args );
        }