0

I'm trying to get the value of an attribute that's on another page. This is what's on the other page that I'm extracting the value from:

<body class="community-top" data-user-id="username" data-token="1234567890" data-language="en">

I want to extract the data-token's value from the page, and alert it to the user. This is the closest I've gotten, after modifying the result from this page:

$.ajax({
url: 'http://example.com',
success: function(response) {
result = $(response).filter(".data-token");
alert(result);
} });

However, it just says "[object Object]", despite the original page saying that using filter() for top-level elements would fix it. I can't seem to convert it to a string properly. Adding "alert(response);" puts the page dump into an alert, which is why I consider this the closest result after all my searching, despite [object Object] still showing up. As I feel that I've done more than my fair share of searching (been doing it for an hour and a half now), I figured I'd ask about this here. So does anyone have a fix?

(I feel like this is painfully obvious, but I'm a newbie to jQuery, have only used it to make simple bookmarklets and scripts.)

Community
  • 1
  • 1
Lane B.
  • 1
  • 2
  • you can access the value of the `data`-attribute by using `$(response).filter("body").data('token');`, `filter(".data-token")` will just filter your response for an element with the class `data-token` – empiric Oct 10 '16 at 18:50
  • 2
    Debugging tip - use `console.log(result)` instead of `alert(result)`. – Jason P Oct 10 '16 at 18:51
  • @empiric That was dumb, I must have forgotten. Replacing the old one with this gives me 'undefined'... getting closer? – Lane B. Oct 10 '16 at 20:41
  • @LaneB. maybe you should check what's inside your `response`. If something is wrappend around the `body` then you could try `.find()` instead of `.filter()` – empiric Oct 10 '16 at 20:47

2 Answers2

0

Use this line instead:

$('.community-top').data('token');
giraff
  • 4,601
  • 2
  • 23
  • 35
0

Is your response in json?

Try this console.log(JSON.stringify(response,null,4)) and then format 'result' accordingly.

Or directly try console.log(JSON.stringify(result,null,4))

Hardik Jain
  • 184
  • 8