Ajax request repeat the same value from PHP

I really searched for information more than a week, but I did not find solution.

I work with ajax in wordpress with wp_ajax,
my target is get images from post type attachment with ajax
I have already made this step, but when I click in the button to call ajax, this show all images attachment, I want to show images sequentially.

Read More

I research info about loop relation to offset and paged, but all info is about pagination post.

This my code in the plugin.php

add_action( 'wp_ajax_nopriv_post_myaction_add_myaction', 'post_myaction_add_myaction' );
add_action( 'wp_ajax_post_myaction_add_myaction', 'post_myaction_add_myaction' );

function post_myaction_add_myaction($size = "full") {

    $post_id = $_POST['post_id'];
    $limit = $_POST['limit'];
    $offset = $_POST['offset'];

            // get images using the get_posts() function
        $images = get_posts(array(
            'numberposts'    => -1, // get all images
            'post_mime_type' => 'image', // so we can get images
            'numberposts' => $limit,
            'post_parent'    => $post_id, // get images attached to the current post
            'offset' => $offset,
            'post_type'      => 'attachment',
            'order'          => 'ASC',
            'orderby'        => 'menu_order' // pull them out in the order you set them as
        ));

        // loop through images and display them
        foreach($images as $image) {
            echo wp_get_attachment_image($image->ID, $size); // returns an image HTML tag if there is one
        }

      die();   

    }

ajax.js

jQuery(".myaction-button").click(function (e) {
    e.preventDefault();

    var post_id = jQuery(this).data('id');
    var limit = 2;
  // offset is the amount of posts which are loaded already
  var offset = 2;
    jQuery.ajax({
        url : postmyaction.ajax_url,
        type : 'post',
        data : {
            action : 'post_myaction_add_myaction',
            post_id : post_id,
            limit: limit,
            offset: offset

        },
        success : function( data ) {
            offset = offset + limit;
            jQuery('#myaction-count').append(data);

        }
    });

    return false;
})

I want to show images in click 2, after click other 2,,,sequentially.

This work but repeat the same value
I have 31 images, but the request just repeat the first and second image, not continue with 3,4 5,6..etc.

I want to be better, if you find something wrong with my code, please tell me how to improve. Thank you very much.

Update:

something strange is happening. I created another post and I attach new images and when I click on the button ajax, I get well the first 4 clicks (2+ 2 + 2 + 2) in the fifth click imagnes begins to repeat, I have reviewed the code and can not find the problem, See the capture of problem: dropbox.com/s/g732sxyn7w4ep1r/example-ajax-data-repeat.jpg?dl=0

¿How can I fixed this problem?

Thanks for reading.

Related posts

2 comments

  1. Ok, so you have several issues. This should fix it:

    add_action( 'wp_ajax_nopriv_post_myaction_add_myaction', 'post_myaction_add_myaction' );
    add_action( 'wp_ajax_post_myaction_add_myaction', 'post_myaction_add_myaction' );
    
    function post_myaction_add_myaction($size = 'full') {
    
        $post_id = $_POST['post_id'];
        $limit = $_POST['limit'];
        $offset = $_POST['offset'];
    
            // get images using the get_posts() function
            $images = get_posts(array(
                'numberposts'    => $limit,
                'post_parent'    => $post_id, // get images attached to the current post
                'offset'         => $offset,
                'post_mime_type' => 'image', // so we can get images
                'post_type'      => 'attachment',
                'order'          => 'ASC',
                'orderby'        => 'menu_order' // pull them out in the order you set them as
            ));
    
            // loop through images and display them
            $out = '';
            foreach($images as $image) {
                setup_postdata( $image );
                $out .= wp_get_attachment_image($image->ID, $size); // returns an image HTML tag if there is one
            }
            wp_reset_postdata();
    
            wp_die($out);
    
    }
    

    Here you had numberposts set to -1 and $limit. You need to remove the -1 because you don’t need to return all the images, only 2 at the time. Also you echoed the results. Don’t echo, return.

    Define an empty variable, then fill it in your loop. Also do a setup_postdata() when using get_posts(). And always reset your postdata once you’ve done with query.

    Next you need to use either die() or wp_die() with the variable to output since this is what actually outputs the response in AJAX call.

    For your jQuery, assuming you’re inside the script where you’ve localized your admin-ajax.php url

    var post_id = $(this).data('id');
    var limit = 2;
    var offset = 0; // offset is the amount of posts which are loaded already
    
    $('.myaction-button').click(function (e) {
        e.preventDefault();
        $.ajax({
            url: postmyaction.ajax_url, // in Twenty sixteen it's screenReaderText.ajax_url
            type: 'post',
            data: {
                action: 'post_myaction_add_myaction',
                post_id: post_id,
                limit: limit,
                offset: offset
            },
            success: function( data ) {
                var $data = $(data);
                $('#myaction-count').append($data);
            },
            complete: function() {
                offset += limit;
            }
        });
    
        return false;
    });
    

    First get the data you have in your divs, set the limit and offset, and then on click execute the ajax call, and when you’re complete increase the offset by limit (number of posts) – this will correctly increase the offset by 2 every time your AJAX call is completed.

    Tested this on Tewnty sixteen and it worked 🙂 Hope this helps ^^

  2. Every time you get in the click action you reset your “offset” value to 2.

    You need to make it a global variable outside of this handler.
    You can also put it in a hidden element if you prefer.

    As suggested, here is a simple snippet of code :

    var offset = 2; // global
    jQuery(".myaction-button").click(function (e) {
        e.preventDefault();
    
        var post_id = jQuery(this).data('id');
    
      // offset is the amount of posts which are loaded already
      var limit = 2;
        jQuery.ajax({
            url : postmyaction.ajax_url,
            type : 'post',
            data : {
                action : 'post_myaction_add_myaction',
                post_id : post_id,
                limit: limit,
                offset: offset
    
            },
            success : function( data ) {
                offset = offset + limit;
                jQuery('#myaction-count').append(data);
    
            }
        });
    
        return false;
    })
    

Comments are closed.