-3

I have a table where I want to get the value of data-url from within a <td>-tag. The content of the table gets first populated via $.ajax GET. Then I use the complete-function to log onto the console the values of data-url. The result is undefined.

$(document).ready(function(){
    $.ajax({ 
        type: "GET",
        cache: false,
        url: "http://localhost:80/server/api/v1/files",
        success: function(data){    
            if (data.error) {
                console.log(data.error)
            } else {
                $("#t1").append(data);        

            }
        },
        error: function(data){            
        },
        complete: function(data){                
            console.log( $('#t1 #f1').data('url') );
        }
    }); 

The table first looks like this:

<table id="t1"></table> 

After the Ajax call it looks like this:

<table id="t1">
  <tr>
    <th>
      Name
    </th>
  </tr>
  <tr>
    <td>
      <a id="f1" data-url="test" href="/Logo.jpg">...</a>
    </td>
  </tr>
</table>

What could be the correct way to get the value of data-url in your oppinion?

Magiranu
  • 299
  • 4
  • 27
  • Your code appears to work fine (where you have the right selectors) - what specific issue are you having? – Jamiec Aug 10 '17 at 11:29
  • `$('#f1').attr('data-url')` will work, why not? Unless you have other things happening in the background that you are not showing, e.g. the table is dynamically loaded/generated and not available during runtime. – Terry Aug 10 '17 at 11:29
  • but if you look at your console it works where you have done the proper selector – Pete Aug 10 '17 at 11:29
  • @MilanChheda what does `prop()` have to do with `data-` attributes? – charlietfl Aug 10 '17 at 11:35
  • My miss, I tagged wrong one. Will revert it. Thanks for checking @charlietfl – Milan Chheda Aug 10 '17 at 11:37
  • 1
    @Jamiec This is odd. It works here in den browser code snipped but not "on my pc". The console write undifined for every `console.log` I have. I have the same jQuery Version and tried Chrome & Firefox. Hmm – Magiranu Aug 10 '17 at 11:40
  • Does the element exist when you run the code? Try `console.log($('#f1').length)` ...shouldn't be zero – charlietfl Aug 10 '17 at 11:41
  • @Magiranu then the code/markup you've shown here is not the same as your actual code. This is why we ask for a [mcve] – Jamiec Aug 10 '17 at 11:42
  • 1
    @charlietfl It exists but gets populated via an `$.ajax GET`. Maybe this doesn't work hand in hand. I make my `console.log` after the Ajax call and thought this would work. – Magiranu Aug 10 '17 at 11:45
  • 1
    The cat went out!!! Ajax is asynchronous. Your elements do not exist (yet) when you run the console.logs. – Louys Patrice Bessette Aug 10 '17 at 11:46

2 Answers2

1

Use data() function to access the data attributes using jQuery. and not attr() or prop(). Though they may work but might not be best suited. See this Question for reference. jQuery.data() Reference

$(document).ready(function(){
    console.log( $('#t1 #f1').data('url') );
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="t1">
<tr>
    <th>
        Name
    </th>
</tr>
<tr>
    <td>
        <a id="f1" data-url="test" href="/Logo.jpg">...</a>
    </td>
</tr>

Hope this helps :)

Manish
  • 4,692
  • 3
  • 29
  • 41
  • Huh? `attr()` will work with HTML5 `data-` attributes. – Terry Aug 10 '17 at 11:30
  • 1
    @Terry yes - `attr()` reads the attribute from the DOM and `data()` reads the live value – Jamiec Aug 10 '17 at 11:30
  • `data()` also reads from the DOM. The only difference is that `data()` is also able to read from the jQuery data object, which `attr()` does not have access to. And `data()` has no write access to HTML5 data attributes. – Terry Aug 10 '17 at 11:32
-1

EDIT2, after comments.

The problem is that you are running this code when the document is ready. But the table appears from an ajax call, which means the element is not there when your code is ran. You should move the function inside your ajax complete event.

EDIT: Use the one you want. Your question includes 2 different ones.

"How is it best to access data attributes?", which got covered here. What you'll want depends mostly on your case but using data attributes with jQuery makes it very interesting to use .data() instead of .attr(). Because .attr() will always return the value stored in the HTML, while data will return the data of the object, which could have been altered. This could even be more than plain text...

"What is the most efficient way to select a dom element", which got many answers everywhere, but to make it short, if your element has an id, use it. If not, try to be the most precise possible... I'll let you read on more about this.

Some of your tries work... See here.

$(document).ready(function(){
    console.log(1, $('#t1 #f1').attr('data-url') ); //works
    console.log(2, $('#t1 f1').attr('data-url') );
    console.log(3, $('#t1 tr td a').attr('data-url') );//works
    console.log(4, $('#t1').attr('data-url') );
    console.log(5, $('#f1').attr('data-url') );//works
    console.log(6, $('#f1').data("data-url") );
    console.log(7, $('#f1').data("url") );//works (is best IMO)
    console.log(8, $('#t1 tr td a f1').attr('data-url') );
    console.log(9, $('#t1 tr td a f1').data('url') );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="t1">
<tr>
    <th>
        Name
    </th>
</tr>
<tr>
    <td>
        <a id="f1" data-url="test" href="/Logo.jpg">...</a>
    </td>
</tr>
Salketer
  • 14,263
  • 2
  • 30
  • 58
  • 2
    This is nothing more than a comment, not an answer – charlietfl Aug 10 '17 at 11:32
  • That was answering "I tried multiple variants but I always get `undefined`." – Salketer Aug 10 '17 at 11:33
  • Your Edit2 is a very good advice. Unfortunately when I put the `console.log` into `complete: function(data){}` the result stays the same. – Magiranu Aug 10 '17 at 12:01
  • Please, re-edit your question to include [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Salketer Aug 10 '17 at 12:05
  • @Salketer I have rewriten the questions. Hope it is okay now :-/ – Magiranu Aug 10 '17 at 12:29
  • The code there should work. Maybe try moving the content of the complete function inside the success function just in case there's weird race conditions, but that shouldn't be needed according to jQuery docs. There has to be something else again... – Salketer Aug 10 '17 at 12:40
  • It works now. I've no clue what I exactly changed but the code looks exactly the same as above fortunately now. Thanks! – Magiranu Aug 10 '17 at 14:07