Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax-returned elements do not trigger in jQuery

Tags:

jquery

php

In the HTML, a dropdown with the ID="project_pick" will fire a change event, sending the selected value to the getallreports.php file. This works. The PHP file does a MySQL lookup and returns values inside some HTML. This also works, and looks great on the page. Here below is the jQuery/ajax code that sends the selected item to the PHP file:

$('#project_pick').change(function(e) {
    $.ajax({
        type: "POST",
        url: "getallreports.php",
        data: "project_id=" + $(this).val(),
        success:function(data){
            $('#reportstable').html(data);
        }
    });
});

The returned data appears inside the specified div, and includes anchor tags with specific IDs that should allow other JQuery events to happen. Snippet of returned HTML:

<table><tr>
    <td>Report 1</td><td><a href="#" id="change_1">click to change</a></td>
    <td>Report 2</td><td><a href="#" id="change_2">click to change</a></td>
</tr></table>

The jQuery code to trigger on the above click event is:

$('#change_1').click(function() {
    alert('Change Report One was clicked');
});

However, clicking the above anchor tag does nothing. Also, the returned HTML does not even appear in the source -- although it shows on the screen and in firebug.

What am I missing? How can I get that click event to fire?

EDIT:

I've been reminded about the .on('click', etc) event (thanks Michael and Zirkms), but when I attempted to add it to my code the dropdown's .change event stopped firing. Perhaps the below code needs a facelift?

$('#project_pick').on(change(function(e) {
    $.ajax({
        type: "POST",
        url: "getallreports.php",
        data: "project_id=" + $(this).val(),
        success:function(data){
            $('#reportstable').html(data);
        }
    });
});
like image 561
cssyphus Avatar asked Feb 18 '26 14:02

cssyphus


1 Answers

On the moment of $('#test').click() code execution #test didn't exist in the DOM, so you didn't bind that handler to somewhere.

Use

$(document).on('click', '#test', function() { ... });

instead

Or (better) if you have a particular node where you insert the retrieved html - use some particular selector rather than $(document) like

$('#reportstable').on(...)

does not even appear in the source

In the "view source" browsers usually show the response from the server as it was retrieved on request, without reflecting JS DOM modifications.

like image 195
zerkms Avatar answered Feb 20 '26 02:02

zerkms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!