Hi I am trying to pass a variable on button click from a php function to javascript. The output is undefined for some reason but at the php function the variable does contain data. Any idea why this is happening?
PHP:
add_filter( 'page_row_actions', 'create_pdf_row_actions', 10, 2 );
function create_pdf_row_actions( $actions, WP_Post $post ) {
if ( $post->post_type != 'item' ) {
return $actions;
}
# $actions['create-pdf'] = "<a href='#?id=".$post->ID."' >Create PDF</a>";
$actions['create-pdf'] = "<a href='#?id=".$post->ID."' >Create PDF".$post->ID."</a>";
return $actions;
}
Javascript:
jQuery(document).ready(function($){
$('.create-pdf').on('click', function () {
alert("button"+ $(this).data("id"));
});
});
Assuming from the piece of code, You can try:
Calling the PHP function within jQuery by using the <?php?>
tags. Since $actions['create-pdf']
is inside an array, use print_r
to output the variable, or use foreach loop
if you have multipile key-value pairs
jQuery's .data()
accesses an element's dataset
but the id
in your link appears to be in the URL fragment of the href
attribute.
You have two options...
Add the appropriate data-id
attribute to your link
$actions['create-pdf'] = sprintf( '<a href="#?id=%1$s" data-id="%1$s">Create PDF%1$s</a>', htmlspecialchars($post->ID) );
$(".create-pdf").on("click", "a[data-id]", function(e) { e.preventDefault(); alert(`button${$(this).data("id")}`); });
Or, extract the id
from the params in the URL fragment
$(".create-pdf").on("click", "a[href]", function(e) { e.preventDefault(); const url = new URL(this.href); const params = new URLSearchParams(url.hash.slice(1)); alert(`button${params.get("id")}`); });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.