2

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!

1
  • e is the click event, not the element. It doesn't have a data attribute. Commented Apr 12, 2013 at 14:35

1 Answer 1

4

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!");
    }
  });
Sign up to request clarification or add additional context in comments.

7 Comments

That worked. So when to use e? Or for what. You say that "e.currentTarget" could be used. Is it better to use $(this) or e.currentTarget. Is it the same?
It's the same, I'd stick with $(this) as it's a little easier to read what's going on, and thus more maintainable.
When you say to use "var url = ..." may it would be better to just use "var this = $(this)" and then use "this.data("url")", "this.somethingelse", not?
That's perfectly viable to do, yep! Just for effeciency though, if you're only using one property, it's best to store just the .data("url") item in the variable rather than the entire $(this) object.
I see. Just another question. In this case I am using this to verify a user. I don't think I should use GET. Maybe Post? But I am not sending any information. Basically, the url has the id of the user so the user property "Verified" will go from true to false. Do I need to set the contenttype? Should I use get or post or put? Thank You
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.