Saracoglu Saracoglu - 2 months ago 7
Javascript Question

How to get the data-esid attribute and POST?

Everything works without

data-esid
, I can not send data in
data-esid
.

Where is the my error?

<a href="#" data-esid="123" data-lname="Saracoglu" onclick="goToWorld();">link1</a>


Javascipt:

function goToWorld() {
var idno = $(this).data("esid");
var last_name = $(this).data("lname");
var dataString = 'ESidNO='+idno+'&last_name='+last_name;

$.ajax({
type:'POST',
data:dataString,
url:'Lib/Path/Page.php',
success:function(data) {
alert(data);
}
});
return false;
}

Answer

I don't see how this could work at all, with or without esid. The problem is that whatever this is in the context of your function, it is not the link you have clicked.

You are also not cancelling the click event, you return false but you are not using that value in your inline click handler. However, that would only cause the page to jump to the top as the link is #.

The easiest way to solve that is by attaching the handler to the link, using for example a class.

The result would be something like:

<a href="#" data-esid="123" data-lname="Saracoglu" class="goToWorld">link1</a>

javascript:

$('.goToWorld').on('click', function(e) {
      // Now $(this) is the link that was clicked
      var idno = $(this).data("esid"),
          last_name = $(this).data("lname");

      // Cancel the default click event
      e.preventDefault();

      $.ajax({
           type: 'POST',
           data: {
                ESidNO: idno, 
                last_name: last_name
           },
           url: 'Lib/Path/Page.php',
           success: function(data) {
               alert(data);
           }
      });
});

Note that I have also replaced the data with an object so that the values will be properly escaped. That will not make a difference in the example code but it will when your values contain characters that have to be escaped in a url.

Comments