Prabin Parajuli
Prabin Parajuli

Reputation: 559

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 ?

Upvotes: 1

Views: 967

Answers (2)

madalinivascu
madalinivascu

Reputation: 32354

this refers to the form not the button

do a find to get the button if the button is in the form tag

jQuery(this).find('button.book').attr('data-id');

Upvotes: 1

H77
H77

Reputation: 5967

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');

Upvotes: 1

Related Questions