Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making jquery .on function work with AJAX loaded content

Tags:

I am having trouble getting an .on 'click' function to work upon AJAX loaded content.

I have worked with the jquery .live before but this is the first time with .on and understand it works in the exact same way so unsure why I am having problems.

Below is the HTML that gives the element to which you click on

    <h1>Press &amp; Media</h1>     <div id="back"></div>     <div id="overlay-content">         <span id="edocs" class="tab"></span>         <span id="news" class="tab"></span>         <span id="partners" class="tab"></span>     </div> 

Below is the function that loads the AJAX content.

    $("#overlay-content").on('click','#news',function() {         var active = 1;         $("#loading").show();         $("#overlay-content").fadeOut(1000, function() {             $.get("http://<? echo ROOT; ?>includes/functions.php", { pressmediaNews: active }, function(data) {                 $("#loading").hide(400);                 $("#overlay-content").empty().append(data).fadeIn(1000);             });         });     }); 

This should load the following HTML

    <div id="news-left-panel">         <h4>News Section</h4>         <ul>             <li id="newsID2" class="newsYear">                 <p>2012</p>                 <ul class="newsMonths" style="display:none">                     <li>Jan                         <ul class="newsArticles" style="display:none">                             <li onClick="newsID(2)">test</li>                         </ul>                     </li>                     <li>Feb</li>                     <li>Mar</li>                 </ul>             </li>             <li id="newsID1" class="newsYear">                 <p>2011</p>                 <ul class="newsMonths" style="display:none">                     <li>Dec                         <ul class="newsArticles" style="display:none">                             <li onClick="newsID(1)">Test</li>                         </ul>                     </li>                 </ul>             </li>         </ul>     </div> 

Now the above code simply wont execute, show any errors etcetera in firebug.

So I'm a bit lost as to why it wont execute, the alert() even does not execute.

like image 258
zealisreal Avatar asked May 02 '12 15:05

zealisreal


People also ask

Can jQuery and AJAX be used together?

jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!

How do you bind events on AJAX loaded content?

You need to use the event delegation for Ajax generated content using jQuery. Use jQuery delegation to attach an event in the dynamically created content by Ajax. The following code snippet shows you how to add/bind/use the jQuery click event on Ajax generated elements.

Is jQuery load AJAX?

The jQuery load() method is a simple, but powerful AJAX method. The load() method loads data from a server and puts the returned data into the selected element.

How does jQuery AJAX works?

Ajax requests are triggered by JavaScript code; your code sends a request to a URL, and when it receives a response, a callback function can be triggered to handle the response.


2 Answers

First make sure you're hitting the target, try this and see if the alert shows :

$(function() {     $(document).on('click', '#news', function() {        alert('ok');     }); }); 

If the alert shows when clicking the #news element, it's ok.

Now to this line:

$.get("http://<? echo ROOT; ?>includes/functions.php", 

You are using the shorthand PHP opening, and that needs to be turned on, you could try

<?php echo ROOT; ?> 

But what the frack is ROOT, never seen that before, and could not find anything in the PHP manual on ROOT, so I tried on my own server with the newest version of PHP, and got an error as 'ROOT' does not exist, instead it assumed it was a string and just echo'ed "ROOT", so your link would look like:

$.get("http://ROOTincludes/functions.php", 

It it's a variable you have defined somewhere yourself, it should start with a dollarsign, if it's something you've defined with define(), make sure it's set up correctly and if it's using something like $_SERVER['DOCUMENT_ROOT']; that's not always something you can access in javascript as it will normally be a folder that is higher then your webroot, and can't be accessed on the clientside but only on the serverside.

Also, the way you have written it, starting with http:// it should be a domain name. Try opening view source in you browser and find your ajax function and see what ROOT actually outputs, as the final ouput will be visible in the source, and if it's set using define() in an included config file etc. you can see that it was set up correctly.

Your javascript would also have to be inside a PHP file for PHP to execute, or you would have to modify your server setup to run JS files thru PHP.

In my opinion just using a path and filename is the right way to do it, try this and pay attention to the console (F12) :

$(document).on('click','#news',function() {     var active = 1;     var XHR = $.ajax({                    type: 'GET',                    url : '/actualpath/includes/functions.php',                    data: { pressmediaNews: active }               }).done(function(data) {                    console.log(data);               }).fail(function(e1, e2, e3) {                    console.log('error : '+e1+' - '+e2+' - '+e3);               });     $("#loading").show();     $("#overlay-content").fadeOut(1000, function() {         XHR.done(function(data) {             $("#overlay-content").empty().append(data).fadeIn(1000);             $("#loading").hide(400);         });     }); }); 
like image 120
adeneo Avatar answered Feb 09 '23 00:02

adeneo


Use a delegate:

$('#overlay-content').on('click', '#newsID2', function() { }); 

This will bind the event on #overlay-content and check for bubbled events if they originated from #newsID2.


As a side-note: You have a typo in your event handler (chikdren should be children) and you should really get rid of this ugly onClick inline event.

like image 26
ThiefMaster Avatar answered Feb 08 '23 23:02

ThiefMaster