gikygik
gikygik

Reputation: 421

How to call a jquery method from PHP page loaded through ajax

I have a page where I am loading a series of buttons into a div using jquery/ajax. This is a script for loading every time the user user scrolls the page. Each of the buttons are clickable and run a jquery function after being clicked. The problem is when I switched to loading the buttons from a different page the now don't call any method. If I switch the buttons to calling a pure javascript function it works just fine but I need the button to call a jquery function as the rest of the script, which is quite long, has been done in jquery.

Here is what I am talking about: Page A:

             $(document).ready(function() {
                 var track_load = 0; //total loaded record group(s)
                 var loading  = false; //to prevents multipal ajax loads
                 var total_groups = '<?php echo $total_groups; ?>';

              $('#results').load("testshareload.php", {'group_no':track_load}, function(result) {
                                 track_load++;
                                 }); //load first group


              $(window).scroll(function() { //detect page scroll
              });

              $('#testerino').on('click', function () {
                    console.log("CALLED");
              });

PAGE B: (testshareload.php)

<?php
    echo "<input type='button' value='Button' id='testerino'>";
?>

It also will not work for me to do this due to the existing code:

function testerino() {
      $(document).ready(function() {
      });
}

What else can I do to solve this problem?

Upvotes: 1

Views: 289

Answers (2)

rjdown
rjdown

Reputation: 9227

Your problem is that you're binding an event to an element that doesn't exist yet.

As per the docs:

Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on()

You have two options:

  1. Create the bind in your .load function instead.

Or as per the docs again:

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.

  1. Use $(document).on('click', '#testerino', function() { ...

Upvotes: 1

Steve K
Steve K

Reputation: 4921

You're creating a click handler for an element that doesn't exist, and this will fail in jQuery. What you need to do is create a DELEGATED handler for the item:

$(document).on('click','#testerino', function () {
    console.log("CALLED");
});

The document accepts the handler being registered, and later when it gets a click event from an element matching the selector #testerino it will fire off the handler.

Upvotes: 1

Related Questions