0

I am returning a set of links from the database via ajax, like so:

function search_friends() {
    who = $('input.search_term').val();
    $.ajax({
        type: "POST",
        url: 'lib/search.php',
        data: {who:who},
        success: function(data) {
            $('.search_results').html(data);
        }
        // dataType: 'json'
    });
    return false;
}

That will return something like:

<div class="search_results">
    <p><b>results:</b></p>
    user1 <a href="add_friend.php?pid=3" class="3">add friend</a>
    <br>
    user2 <a href="add_friend.php?pid=4" class="4">add friend</a><br><hr>
</div>

But as soon as the page loads (before the search is done), I have something like:

$('.search_results a').click(function() {
    alert('code');
});

But that doesn't work because .search_results div is returned via ajax.

How to solve this problem?

Ollicca Mindstorm
  • 608
  • 1
  • 11
  • 24
  • Possible duplicate of http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements – krishwader Jul 25 '13 at 14:43
  • i'd make the
    a static div and put the results into it. so you can bind the events because it will always exist.
    – abc123 Jul 25 '13 at 14:43

2 Answers2

3

You are trying to bind event to elements that does not exists at the time of binding. You need to use on to bind click event with event delegation.

$(document).on('click','.search_results a', function() {
    alert('code');
});

Delegated events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

Adil
  • 146,340
  • 25
  • 209
  • 204
1

You should use jQuery on for dynamic content.

$(document).on('click', '.search_results a', function(e){
 alert('code');
});
Konsole
  • 3,447
  • 3
  • 29
  • 39