Prabin Parajuli Prabin Parajuli - 1 month ago 17
PHP Question

jQuery dynamic id value returning UNDEFINED in WordPress

I am trying to get WordPress

Post Id
dynamically as variable in
jQuery
. However, it is returning the value undefined when I try to debug in
console
. Can anyone help me on this ?

Here's the code:

data-id attribute displaying id of the current post

<?php $id = get_the_id(); ?>

<button data-id="<?php echo $id; ?>" type="button" class="book btn btn-danger">
Submit
</button>


My jQuery

jQuery(document).ready(function(jQuery){
jQuery('.packageForm').submit(packageSubmit);
function packageSubmit(){
var id = jQuery(this).attr('data-id');
var ceccForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "wp-admin/admin-ajax.php",
data: ceccForm,
success:function(data){
console.log(id);
console.log(data);
jQuery(".response").html(data);
jQuery(".packageForm")[0].reset();
jQuery('body').removeClass('modal-open');
}
});

return false;
}
});


Here, I am using
var id = jQuery(this).attr('data-id');
to get the value of the attribute
data-id
dynamically. It's showing the message Undefined Value in the browsing console.

Any help ?

H77 H77
Answer

Here this is actually referring to your form packageForm since you're calling it from the submit function of the form, and it won't have the attribute you've set to the button.

You could probably do something like this

var id = jQuery(this).find('button.book').data('id');