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"));
});
});
2
Answers
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, useprint_r
to output the variable, or useforeach loop
if you have multipile key-value pairsjQuery’s
.data()
accesses an element’sdataset
but theid
in your link appears to be in the URL fragment of thehref
attribute.You have two options…
Add the appropriate
data-id
attribute to your linkOr, extract the
id
from the params in the URL fragment