Ollicca Mindstorm
Ollicca Mindstorm

Reputation: 608

How to setup click events on results returned via ajax?

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?

Upvotes: 0

Views: 50

Answers (2)

Konsole
Konsole

Reputation: 3475

You should use jQuery on for dynamic content.

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

Upvotes: 1

Adil
Adil

Reputation: 148120

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.

Upvotes: 3

Related Questions