4

Is there any way to run a script again after an ajax call?

I have a photoswipe (lightbox) jquery plug-in I call like this:

jQuery(document).ready(function($){

    if( $('.img-frame a').length > 0 ){

        var myPhotoSwipe = $(".img-frame a").photoSwipe();

     }
});

I also have an ajax 'load more posts' function, and obviously photoswipe doesn't target images loaded after the first page load.

I don't have much ajax knowledge, any help on this? Thanks

UPDATE: Here's the 'load more' script:

jQuery(document).ready(function($) {

    // The number of the next page to load (/page/x/).
    var pageNum = parseInt(djwd_load_posts.startPage) + 1;

    // The maximum number of pages the current query can return.
    var max = parseInt(djwd_load_posts.maxPages);

    // The link of the next page of posts.
    var nextLink = djwd_load_posts.nextLink;

    /**
     * Replace the traditional navigation with our own,
     * but only if there is at least one page of new posts to load.
     */
    if(pageNum <= max) {
        // Insert the "More Posts" link.
        $('#content')
            .append('<div class="lp-placeholder-'+ pageNum +'"></div>')
            .append('<p id="lp-load-posts" class="long-button"><a href="#">Load More Posts<i class="icon-chevron-down icon-large"></i></a></p>');

        // Remove the traditional navigation.
        $('#nav-below').remove();
    }


    /**
     * Load new posts when the link is clicked.
     */
    $('#lp-load-posts a').click(function() {

        // Are there more posts to load?
        if(pageNum <= max) {

            // Show that we're working.
            $(this).text('Loading posts...');

            $('.lp-placeholder-'+ pageNum).load(nextLink + ' .post',
                function() {

                    $( this ).hide().fadeIn(700);

                    // Update page number and nextLink.
                    pageNum++;
                    nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);

                    // Add a new placeholder, for when user clicks again.
                    $('#lp-load-posts')
                        .before('<div class="lp-placeholder-'+ pageNum +'"></div>')

                    // Update the button message.
                    if(pageNum <= max) {
                        $('#lp-load-posts a').text('Load More Posts');
                    } else {
                        $('#lp-load-posts a').text('No more posts to load.');
                    }
                }
            );
        } else {
            $('#lp-load-posts a').append('.');
        }   

        return false;
    });
});

I call it in Wordpress functions.php this way:

 function djwd_ajax_load_init() {
    global $wp_query;

    if( !is_singular() ) {
        wp_enqueue_script('ajax-load-posts', get_template_directory_uri() . '/js/ajax-load-posts.js', array('jquery'), true );

        $max = $wp_query->max_num_pages;
        $paged = ( get_query_var('paged') > 1 ) ? get_query_var('paged') : 1;

        wp_localize_script(
            'ajax-load-posts',
            'djwd_load_posts',
            array(
                'startPage' => $paged,
                'maxPages' => $max,
                'nextLink' => next_posts($max, false)
            )
        );
    }
 }
 add_action('template_redirect', 'djwd_ajax_load_init');
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
djwd
  • 315
  • 2
  • 5
  • 15

6 Answers6

2

Put it in a function, call in on pageload and in your ajax call.

function setMyPhotoSwipe() {
    var $targets = $('.img-frame a').not('.photo-swipe');

    if($targets.length > 0 ){
        $targets.addClass('photo-swipe').photoSwipe();
    };
};

jQuery(document).ready(function($){
    setMyPhotoSwipe();
});

By the way, if dont't need variable myPhotoSwipe, then you dont't have to set it. You are also using $('.img-frame a') twice, so cache the result.

And your load call:

$('.lp-placeholder-'+ pageNum).load(nextLink + ' .post',
            function() {

                $( this ).hide().fadeIn(700);

                // Update page number and nextLink.
                pageNum++;
                nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);

                // Add a new placeholder, for when user clicks again.
                $('#lp-load-posts')
                    .before('<div class="lp-placeholder-'+ pageNum +'"></div>')

                // Update the button message.
                if(pageNum <= max) {
                    $('#lp-load-posts a').text('Load More Posts');
                } else {
                    $('#lp-load-posts a').text('No more posts to load.');
                }

                // New content has been loaded and insertet, so set up photo swipe
                setMyPhotoSwipe();
            }
        );
BenMorel
  • 34,448
  • 50
  • 182
  • 322
iappwebdev
  • 5,880
  • 1
  • 30
  • 47
  • Ok thanks, I understand the logic. What do I have to set for "URL:" though? – djwd Dec 14 '12 at 13:55
  • Yeah that was I was missing. Ok I'm almost there, it works only if I duplicate the full function in ajax-load-more.js, otherwise I get setMyPhotoSwipe(); is not defined. (the first photoswipe call it's in another js file). But if I duplicate the function I get this error Uncaught Code.PhotoSwipe.activateInstance: Unable to active instance as another instance is already active for this target. Even though everything works, I don't think it's very 'elegant' – djwd Dec 14 '12 at 14:34
  • (sorry I tried to format better my comment but I ran out of 5mins time) – djwd Dec 14 '12 at 14:41
  • Well then you have have to mark those links already loaded before, I updated my answer, see function `setPhotoSwipe()`. Regarding your error: put the function defintion outside `jQuery(document).ready`. – iappwebdev Dec 14 '12 at 14:47
  • I just set the function like this: **$.fn.setMyPs = function()...** and ran it like you said in first place on my ajax call and now everything works flawless without errors. Many thanks @Simon and everyone. – djwd Dec 14 '12 at 15:08
2

There is no delegation for plugin, its up to author's plugin to incorporate it. Why not cheating: (sorry, cannot test code and not sure its relevant to photoSwipe plugin)

jQuery(document).ready(function($){

    $(this).on('mousedown','.img-frame a',function(){ //document or better parent container// mousedown or any relevent event use by photoSwipe
          if(!$(this).data('swiped')) {
              $(this).data('swiped',true).photoSwipe();
          }
    });

});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1
$.ajax({
    url: 'url/test.php',
    success: function(data) { // also gets response from php and can be manipulated if required!
        setMyPhotoSwipe();
    }
});
Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62
1

Sorry I'm a novice in jquery... How about using ajaxComplete()

http://api.jquery.com/ajaxcomplete/

Once I had to execute a function after ajax call... and ajaxComplete() did the trick...

$(document).ready(function(){

  function some_function()
  {
  //---- this function to be called after ajax request...
  }

  $( document ).ajaxComplete(function() {

    some_function();

  });
})
AlexVogel
  • 10,601
  • 10
  • 61
  • 71
Yogesh
  • 19
  • 1
  • Thanks! After installing **Ajax Load More Posts WP Plugin**, the magnific pop up jquery plugin init function was not working for the post images which were being loaded after the ajax call made by the WP plugin, so I used this function on my page template with wp constants to load the function only on my custom post type page template and it worked. – Adriano Monecchi Aug 21 '14 at 03:51
0

I would suggest the below

 jQuery(document).ready(InitializeSettings);

also call the same in ajax calls

  ajax_success_function(){ // depends on your ajax call
   InitializeSettings();
  }


  function InitializeSettings(){

    if( $('.img-frame a').length > 0 ){
       var myPhotoSwipe = $(".img-frame a").photoSwipe();
     }
  }
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120
0

Like Morpheus said.

Create a seperate function that put your code in that.

You can call that function inside your $(document).ready()

Then use that same function in your ajax success path (check documentation: http://api.jquery.com/jQuery.ajax/).

Alternatively you can use this: http://api.jquery.com/ajaxStop/

It will facilitate you to use the same function when your every Ajax Call stops.

xray1986
  • 1,148
  • 3
  • 9
  • 28