-4

I cannot get the id from links calling the same ajax function. More than 30 links are generated dynamically, as follows:

<a href="javascript:void(0)" id="105">Item 105</a>
<a href="javascript:void(0)" id="379">Item 379</a>
<a href="javascript:void(0)" id="534">Item 534</a>

This is my latest attempt, after much googling, including this.

$(this).click(function() {
  var $id = $(this).attr('id');
  $.ajax({
    url: "somefile.asp",
    data: {
      sellerid: <%=sellerid%>,
      uid: <%=uid%>,
      itinid: $id
    },
    success: function(result) {
      $("#content").html(result);
    }
  });
});

The ajax works fine (but with fixed result) for each link when I test with for example:

var $id = 379;
Community
  • 1
  • 1
Paul
  • 117
  • 2
  • 9
  • `$(this).click(function(){` - and what is `this` exactly? You sure you dont want `$("a").click(function() {` – tymeJV Aug 24 '16 at 14:46
  • Ok, so, you have an attempt, and the ajax works, so what's the problem? Break it down. I'm pretty sure you can omit ajax from this question. – Kevin B Aug 24 '16 at 14:48
  • 3
    Works fine for the elements themselves: https://jsfiddle.net/j396dd79/ What are you actually attaching that click handler to? – David Aug 24 '16 at 14:48
  • $(this).click(function() was the result of tons of googling too: how to attach same ajax function to various buttons/links. But just checked, it applies to any click anywhere so needs refining. – Paul Aug 24 '16 at 15:01
  • 1
    in other words, you want to know how to use jquery. http://learn.jquery.com http://api.jquery.com – Kevin B Aug 24 '16 at 15:01
  • Ajax works only when value of $id fixed, and only gives the value for that $id. I need it to give different results depending on $id – Paul Aug 24 '16 at 15:02
  • As mentioned, I have googled endlessly on this, I thought this is forum for help not criticism. So far has been much help, but newbies are expected to know all which is an odd approach – Paul Aug 24 '16 at 15:05
  • Use `console.log(this)` to debug what `this` actually is. – gre_gor Aug 24 '16 at 15:42
  • @David: it worked 100% with $('a') instead of $(this). Not sure why but great. Now just have to get the right selector as currently every link on the page runs the ajax! But thanks, that is definitely a big improvement. If you can put that as a separate answer I can mark as correct? – Paul Aug 24 '16 at 15:52

3 Answers3

1

I post the answer, helped by several good comments, hindered by 2 others who IMHO forget the forum is to help people not criticise. This costs me -4 points but still worthwhile!

$('#templatelist a').click(function(){
    var $id = $(this).attr('id');
    //var $id = $( this ).data( 'id' );
    $.ajax({url: "trips-check.asp", data: {sellerid: '<%=sellerid%>', uid: '<%=uid%>', itinid: $id}, success: function(result){
        $("#content").html(result);
    }});
});

In summary, $(this) worked in terms of enabling the ajax but did not get the variable $id. $('a') worked fully, but the links had to be enclosed in a div with id templatelist so only those links triggered the ajax. Basic stuff yes, but still new for newbie me.

Paul
  • 117
  • 2
  • 9
0

Note #1:

Do not use click or bind if your items are generated dynamically.

Note #2:

If you use a old jquery version, you should use live(version deprecated: 1.7, removed: 1.9).

Well, you can use live or on(best option) maybe you can fix it.

Example (best way):

You html(generated dynamic):

<ul id="mylist">
    <li><a href="" id="...">...</a></li>
    <li><a href="" id="...">...</a></li>
    <li><a href="" id="...">...</a></li>
    <li><a href="" id="...">...</a></li>
    <li><a href="" id="...">...</a></li>
</ul>

You JS:

$('#mylist').on('click', 'a', function(){
    alert( $(this).attr('id') );
})

Old way( poor way; deprecated ):

$('#mylist li a').live('click', function(){
    alert( $(this).attr('id') );
})

Learn here: http://api.jquery.com/on/

And here: https://stackoverflow.com/a/11878976/901197

Full example:

JS:

$(document).ready(function(){
  var elements = [
    {id:1, text: "A", data: 'Hi'},
    {id:2, text: "B", data: 'Hello'},
    {id:3, text: "C", data: 'Hola'},
    {id:4, text: "D", data:'Ciao'},
    {id:5, text: "E", data:'Priviet'},
    {id:6, text: "F", data: 'Bonjour'},
    {id:7, text: "G", data:'Hallo'},
    {id:8, text: "H", data:'Olá'}
  ];
  $.each(elements, function( index, element ){
    var li = document.createElement('li'),
        a = document.createElement('a');
    $(a).attr('id', element.id)
    $(a).data('hello', element.data)
    $(a).text(element.text)
    $(li).append(a)
    $('#dynamics').append( li )
  })
  
  
  $('#dynamics').on('click', 'a', function(){
    var self = $(this);
    alert('You clicked on ' + self.text() + '. ' + self.data('hello') + ' id #' + self.attr('id') );
  })
});

HTML:

<ul id="dynamics"></ul>

Try here:

http://codepen.io/olaferlandsen/pen/rLEZqw

Community
  • 1
  • 1
Olaf Erlandsen
  • 5,817
  • 9
  • 41
  • 73
  • Tried this but no alert appears: $('#mylist').on('click', 'a', function(){ alert( $(this).attr('id') ); }) – Paul Aug 24 '16 at 15:39
0

Generate data-id attribute, not just id, for sake of html validity

<a href="javascript:void(0)" data-id="105">Item 105</a>
<a href="javascript:void(0)" data-id="379">Item 379</a>
<a href="javascript:void(0)" data-id="534">Item 534</a>

Register event for generated links in this way

$( 'document' ).on( 'click' , 'a[data-id]', function( evt ) {
    evt.preventDefault();
    var $id = $( this ).data( 'id' );
    $.post( 'somefile.asp' , { sellerid: '<%=sellerid%>',
                               uid: '<%=uid%>',
                               itinid: $id
                             } , function( result ) {
         $( "#content" ).html( result );
    }, 'html');
});
  • I see you put all variables in ' ', will check this. Also tried using same as data-id, used a different approach to use (which failed), will try yours – Paul Aug 24 '16 at 15:08
  • Ok. But do not use parentheses on $id, this was my mistake. –  Aug 24 '16 at 15:10
  • Thanks, you are right. Had previously tried with similar data approach but extracted differently (& did not work). Tried with yours (var $id = $( this ).data( 'id' );) with my .ajax as above but not working. Then tried your full script but not working at all (am using Chrome debugger). – Paul Aug 24 '16 at 15:28
  • Try replacing line $( "#content" ).html( result ); with console.log( $id + '\n' + result ); –  Aug 24 '16 at 15:37
  • Thanks Waldemarlce, very helpful. I have not tried, as suggestion above, to put $('a') instead of $(this) worked 100% giving correct ajax result for each button. Just have to change the selector to prevent all links on the page calling the ajax – Paul Aug 24 '16 at 15:55
  • Ah... Edited, added preventDefault. –  Aug 24 '16 at 16:09