How can I pass a variable to wp_ajax action?
I'm writing a plugin that pulls data from an external API and inserts it into a bbPress topic. Here's some sample code:
function bbp_ajax() {
$topic_id = bbp_get_topic_id();
$the_issue_key = get_post_meta( $topic_id, 'bbp_jira_issue_field', true);
$nonce = wp_create_nonce( 'theNonce' );
// jQuery AJAX Code, actions bbpAjax...
}
add_action ( 'bbp_template_before_replies_loop', 'bbp_ajax');
function get_ajax_content() {
check_ajax_referer( "theNonce" );
$api_url = get_option( 'jifbs_url' );
$fullurl = $api_url.$the_issue_key;
$username = get_option( 'jifbs_username' );
// Then I pull in the data with cURL and echo it. But I need $the_issue_key to complete the API auth
}
add_action( 'wp_ajax_bbpAjax', 'get_ajax_content' );
add_action( 'wp_ajax_nopriv_bbpAjax', 'get_ajax_content' );
I can't figure out how to pass $the_issue_key
into the get_ajax_content
function. I've tried setting it as a global (shudder) but it always returns null.
$the_issue_key = get_post_meta( $topic_id, 'bbp_jira_issue_field', true);
run in the get_ajax_content function returns null.
Is there something specific to a wp_ajax
action that I might need to know - or am I missing something really obvious?
Answers 1
You'd need to put the variable's value onto the page so that javascript can pass it back to PHP using ajax. Ajax functions are a completely separate "page load" so even if you made it global it won't work. The best way to do this is using "wp_localize_script" (https://codex.wordpress.org/Function_Reference/wp_localize_script)
Here's an full example of how you could do it:
And then in your javascript file do something like this: