简体   繁体   中英

AJAX load more function multiplies the old data?

I have a PHP code that creates a JSON data from wordpress posts in the database.

I load this JSON on my html page using AJAX.

The above works fine.

Now I need to add a "Load More" button so everytime its pressed, we load another 10 posts and append/add them to the ones that were already loaded WITHOUT having to delete the old ones and re-adding them.

So this my AJAX code for loading more:

var i = 0;
$(document).on("click", ".loadMoreBtn", function () {
    $.ajax({
        url: 'https://some-domain.com/index.php?t=' + mainCat + '&page=' + i + '',
        dataType: 'json',
        jsonp: 'jsoncallback',
        timeout: 5000,
        success: function (data, status) {

            if (!$.trim(data)) {

            }
            else {
            }

            $.each(data, function (pi, item) {

                var id = item.id;
                var img = item.img;
                var title = item.title;
                var date_added = item.date_added;

                var item = '' + title + '';

                $('.myDiv').before(item);
                i++;
            });

        },

        error: function () {
            //error handling////
        }
    });
});

And this is my PHP code:

<?php
    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/json');
    $path = $_SERVER['DOCUMENT_ROOT'];
    include_once $path . '/wp-config.php';
    include_once $path . '/wp-load.php';
    include_once $path . '/wp-includes/wp-db.php';
    include_once $path . '/wp-includes/pluggable.php';

      $t = $_GET['t'];
      $page = $_GET['page'];
      $posts = get_posts(array(
      'posts_per_page' => $page, //add -1 if you want to show all posts
      'post_type' => 'post',
      'post_status' => 'publish',
      'tax_query' => array(
                  array(
                        'taxonomy' => 'category',
                        'field' => 'slug',
                        'terms' => $t //pass your term name here
                          )
                        ))
                       );



    $output= array();
    foreach( $posts as $post ) {

        $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );

        $mysqldate = $post->post_date;
        $phpdate = strtotime( $mysqldate );
    $mysqldate = date( 'F d Y', $phpdate );
        // Pluck the id and title attributes
        $output[] = array( 'id' => $post->ID, 'title' => $post->post_title, 'date_added' => $mysqldate, 'img' =>$feat_image );
    }

    echo json_encode( $output );

When I click on the ' Load More ' button, it acts strangely! it basiclaly adds the old data and multiplies the same ones and adds/loads some new ones as well.

I know I am missing something in my PHP code but I couldn't figure out what.

Could someone please advice on this issue?

Thanks in advance.

The error is in your wordpress query. "posts_per_page" set how many posts will be loaded. Set that as how many post should be loaded like 12 or something.

The parameter your want to set as your $page parameter is "paged". Eg. $query = new WP_Query( array( 'paged' => 6 ) ); // page number 6

https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters

您也可以使用 WP API 而不是自己滚动

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM