Solution 1 :

You don’t need .each, because $(".button").on("click") already add handlers to all .button. In your case, it loops every .button and every time it will add handlers, to them all, on each turn.

According to jQuery docs, the .post() expect object or string as the second argument:

$(document).ready(function(){
   $(".button").on("click",function(){
     var touserId = $(this).attr("data-touserid");
     $.post("to.php", { term: touserId });
   }); 
});

If you’re using data-touserid="id" on the button, you should use .attr(), because .data('touserid') is not the same as .attr('data-touserid').

<button class="button" data-touserid="touserid">send</button>

Problem :

This is my jquery code that takes the data attribute of a specific button having the class name “.button”. I’m trying to post this data attribute to a PHP file having the name “to.php”. I’ve also tried this with $.ajax method but in PHP it says the term is undefined when I echo $_POST[‘term’]. Can someone help me in posting data attributes to a PHP file?

$(document).ready(function(){
  $(".button").each(function() {
    $(".button").on("click",function(){
      term = $(this).data("touserid");
      $.post("to.php",term);
    });  
  });
});
<?php
  $to = $_POST['term'];
  echo $to;
?>

Comments

Comment posted by jquery posting data attribute to the next page

Does this answer your question?

Comment posted by Hassan Khan

First of all thanks for your answer but here I’ve again that message “Undefined index: term in line no.—“

Comment posted by Hassan Khan

Is there any other solution you have?

Comment posted by artanik

check the answer, hope this is helpful 🙂

Comment posted by Hassan Khan

Bro still not working. One more thing that I wanna tell you that I used data-touserid=”‘.$row[“Email”].'”

By