Miguel Moura
Miguel Moura

Reputation: 39364

Get data attribute value ... data is returning null

I have the following tag:

<a href="#" class="Test" data-url="/api/users/unlock">Test</a>

And the following JQuery:

$('a.Test').click(function (e) {
  alert(e.data); >> This returns null
  jQuery.support.cors = true;
  $.ajax({
    url: e.data('url'),
    type: 'GET',
    dataType: 'json',
    success: function (data) {
      alert(data)
    },
    error: function () {
      alert("Failure!");
    }
  });

});

Basically, I am trying to use in the Ajax call the url of data-url.

This is not working and when I try alert(e.data) I get null.

What am I doing wrong?

Thank You!

Upvotes: 2

Views: 4072

Answers (1)

Chris Dixon
Chris Dixon

Reputation: 9167

You need to use the data() function, such as:

You need $(this).data("url");

And, to note, $(this) will lose scope inside your $.ajax call, so be sure to set a variable outside it and use that instead. i.e.

$('a.Test').click(function (e) {
  var url = $(this).data("url");
  jQuery.support.cors = true;
  $.ajax({
    url: url,
    type: 'GET',
    dataType: 'json',
    success: function (data) {
      alert(data)
    },
    error: function () {
      alert("Failure!");
    }
  });

Upvotes: 4

Related Questions