Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I tried something like the following but if the page I'm loading has javascript it's not running because the elements are created after page load. When the javascript is something I wrote I simply call the function again after load() and it's ok, but what can I do for the plugins the page has? Like contact forms etc?

Whats is the correct way doing ajax calls in wordpress so as my rest javascript wont brake? Thanks!

$('#subpage_arrows a').live("click", function(){

      $('.content_inside').wrap('<div id="ajax_content" />');
      $('#ajax_content').css('height',$('.content_inside').height());

      var toLoad = $(this).attr('href')+' .content_inside';  

      $('.content_inside').fadeOut('fast',loadContent);

      $('#load').remove();  
      $('#content').append('<div id="load">Loading...</div>');  
      $('#load').fadeIn(900);  
      window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);  
      function loadContent() {  
          $('#ajax_content').load(toLoad,'',showNewContent());
      }  
      function showNewContent() {  
          $('#ajax_content').hide().fadeIn(1000,hideLoader()).css('height','auto');

      }     
      function hideLoader() {  
          $('#load').fadeOut('normal');
      }  
      return false;     

});
share|improve this question
add comment

1 Answer

Short answer: it's not possible what you're asking, in the right way.

Because the DOM is changed, the elements that were removed had their events attached on them removed also, so you need to run that javascript again on the new elements. And if you have no control over those plugins and their javascript, then you'll have to do this the ugly way. This means that you need to search for <script> tags inside the ajax response and inject them in the document.

What's even worse, you will need to bypass browser "security" measures by carefully passing strings like '<scr' + 'ipt>' to $.append() (or whatever innerhtml wrapper you use). Also avoid executing any javascript code that contains document.write calls (here's why).

As a side note, try to avoid $.live in favor of $.delegate:

$('#subpage_arrows a').live("click", ... => $('#subpage_arrows').delegate("a", "click", ...

(you narrow down the dom selection)

share|improve this answer
1  
And as of jQuery 1.7, delegate() has been superseded by the on() method. –  Geert Nov 16 '11 at 14:15
    
true. So then I guess click < delegate < on –  onetrickpony Nov 16 '11 at 20:28
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.