0

I am trying to fetch more posts on click via ajax. In my functions I have localised the script

wp_enqueue_script( 'news', get_template_directory_uri().'/news/js/news.js', '', '', true );

//Localise script for ajax call
wp_localize_script( 'news', 'ajax_posts', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'noposts' => 'No Older Posts Found',
));

My Function for querying posts

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 2;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;


    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'paged'    => $page
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .='<article class="post-container clearfix">
                    <div class="post-inner clearfix">

                    <div class="post-image">
                        '.get_the_post_thumbnail().'
                    </div>
                    <h1>'.the_title().'</h1>
                    <span class="date">Date: '.get_the_date().'</span>
                    <br>
                    <span class="author">Author: '.the_author().'</span>
                    <br>
                    '.get_custom_excerpt(get_the_content()).'
                    <a class="read-more" href="'.get_the_permalink().'" title="Read More"><img src="'.get_template_directory_uri().'/news/img/read-more.png" alt="Read More"></a>
                    </div>
                </article>';
    endwhile;
    endif;
    wp_reset_postdata();
    echo $out;
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

and then my jQuery

jQuery(document).ready(function(){

    var ppp = 2; // Post per page
    var pageNumber = 1;


    function load_posts(){
        pageNumber++;
        var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
        jQuery.ajax({
            type: "POST",
            dataType: "html",
            url: ajax_posts.ajaxurl,
            data: str,
            success: function(data){

                console.log(data);

                var $data = jQuery(data);
                if($data.length){
                    jQuery(".posts-wrapper").append($data);
                    jQuery(".load-more").attr("disabled",false);
                } else{
                    jQuery(".load-more").attr("disabled",true);
                }
            },
            error : function(jqXHR, textStatus, errorThrown) {
                $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
            }

        });
        return false;
    }

    jQuery(".load-more").on("click",function(e){ // When btn is pressed.

        jQuery(".load-more").attr("disabled",true); // Disable the button, temp.
        load_posts();

        e.preventDefault();

    });

});

The ajax response is always 0. Could anyone help please.

6
  • And what should it be?
    – prosti
    Commented Jan 18, 2017 at 13:43
  • die($page) looks to me like killing the request from the top. Is that for debugging? You could verify the whole request with wp_die( var_dump( $_REQUEST ) ) to make sure..
    – Ismail
    Commented Jan 18, 2017 at 13:44
  • Yeah sorry that was added when I was trying to figure out if it was ever reaching the ajax_posts function. When I check in network the the ajax request is successful and it's hitting the success callback of the ajax call but it looks like for some reason the code in ajax_posts is not returning the next 2 posts as expected. Commented Jan 18, 2017 at 13:54
  • It should be the next 2 posts Commented Jan 18, 2017 at 13:55
  • I found that this error usually happens when you don't set the action. That doesn't seem to be your case, but could it be the way your data string is setup? Have you tried passing it as an object literal { pageNumber: pageNumber, ppp: ppp, action: more_post_ajax }? Commented Jan 18, 2017 at 14:20

2 Answers 2

2

Try die() function in the end of PHP function. It will helps.

UPD: Ive made some simple version of your problem code to check it and it works. I think it will helps you. You are able to change inner PHP script to your logic and it wont returns 0.

PHP:

function more_post_ajax(){
  echo "Hello";
  die();
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

function custom_scripts_init(){
  wp_enqueue_script( 'custom', get_template_directory_uri().'/assets/js/custom.js', array('jquery') );
  wp_localize_script( 'custom', 'ajaxPosts', array(
    'customUrl' => admin_url( 'admin-ajax.php' ),
    'noposts' => 'No Older Posts Found',
));

}
add_action('wp_footer', 'custom_scripts_init');

JQuery:

jQuery(document).ready(function(){
jQuery("#page").append("<button type='button' class='load-more'/>");
var ppp = 2; // Post per page
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    jQuery.ajax({
        type: "POST",
        dataType: "html",
        url: ajaxPosts.customUrl,
        data: str,
        success: function(data){
            console.log(data);
        },
        error : function(jqXHR, textStatus, errorThrown) {
            //$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

jQuery(".load-more").on("click",function(e){ // When btn is pressed.

   // jQuery(".load-more").attr("disabled",true); // Disable the button, temp.
    load_posts();

    e.preventDefault();

});

});

6
  • Using wp_die() is even better !
    – Sladix
    Commented Jan 18, 2017 at 14:45
  • Tried all of these. It's going to be something really easy I'm sure of it but it is driving me nuts. Commented Jan 18, 2017 at 15:01
  • Have you tried to print your WP_Query object? Commented Jan 18, 2017 at 15:07
  • I don't think it's hitting the function more_post_ajax for whatever reason. Commented Jan 18, 2017 at 15:12
  • if I add die($_POST['ppp']); right at the top of the function more_post_ajax then it shoud definitely return that variable but it isn't Commented Jan 18, 2017 at 15:14
0

In case anyone comes to this, I just thought I would add what the issue was.

I inherited the job from another developer and for reasons I will never understand there was ob_start at the top of the functions file. This was causing the ajax request to fail.

Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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