最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Using Ajax to load more posts | Help me change the wording on my button to notify the user

programmeradmin4浏览0评论

I am having bit of a brain melt situation trying to carry across a style of code I used on a previous website where I would change the wording on the button the user clicks to load more. I have created a working example on a filter button but can't seem to see how I can apply this to my load more button.

Currently the user will click load more, wait 5 seconds, then the new content will append to the old.

I wish for them to click the load more, the wording will change to loading, then when the content loads the wording will revert to load more.

Here is an example I have working (don't amend this code) on some filters...

jQuery(function(n) {
    n("#advanced-filterform").submit(function() {
        var e = n("#advanced-filterform");
        return n.ajax({
            url: e.attr("action"),
            data: e.serialize(),
            type: e.attr("method"),
            beforeSend: function(t) {
                e.find("button").text("Applying Filters...")
            },
            success: function(t) {
                e.find("button").text("Apply filters"), n("#response").html(t)
            }
        }), !1
    })
})

I wish to use a similar technique to this block of code (edit this block of code):

var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
jQuery(function($) {
    $('#load-more').click(function() {
        var data = {
            'action': 'load_posts_by_ajax',
            'page': page,
            'security': '<?php echo wp_create_nonce("load_more_posts"); ?>'
        };

        $.post(ajaxurl, data, function(response) {
            if(response != '') {
                $('.testimonials').append(response);
                page++;
            } else {
                $('.load-more-posts').hide();
            }
        });
    });
});

I am fairly new to the wonders of Ajax so would appreciate any commentary you can provide while you answer!

Big thanks to any contributors, Jason.

I am having bit of a brain melt situation trying to carry across a style of code I used on a previous website where I would change the wording on the button the user clicks to load more. I have created a working example on a filter button but can't seem to see how I can apply this to my load more button.

Currently the user will click load more, wait 5 seconds, then the new content will append to the old.

I wish for them to click the load more, the wording will change to loading, then when the content loads the wording will revert to load more.

Here is an example I have working (don't amend this code) on some filters...

jQuery(function(n) {
    n("#advanced-filterform").submit(function() {
        var e = n("#advanced-filterform");
        return n.ajax({
            url: e.attr("action"),
            data: e.serialize(),
            type: e.attr("method"),
            beforeSend: function(t) {
                e.find("button").text("Applying Filters...")
            },
            success: function(t) {
                e.find("button").text("Apply filters"), n("#response").html(t)
            }
        }), !1
    })
})

I wish to use a similar technique to this block of code (edit this block of code):

var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
jQuery(function($) {
    $('#load-more').click(function() {
        var data = {
            'action': 'load_posts_by_ajax',
            'page': page,
            'security': '<?php echo wp_create_nonce("load_more_posts"); ?>'
        };

        $.post(ajaxurl, data, function(response) {
            if(response != '') {
                $('.testimonials').append(response);
                page++;
            } else {
                $('.load-more-posts').hide();
            }
        });
    });
});

I am fairly new to the wonders of Ajax so would appreciate any commentary you can provide while you answer!

Big thanks to any contributors, Jason.

Share Improve this question asked Oct 8, 2019 at 10:54 Jason Is My NameJason Is My Name 3782 gold badges7 silver badges21 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

The first block you provided can be sufficiently updated to be used with your code but see my example below:

Start of by setting up your WordPress function to load your scripts (inside functions.php) and set the global ajax script variable to use later. I am breaking it down into sections since this would the correct way of doing it:

function js_enqueue_scripts() {
    wp_enqueue_script("my-ajax-handle", get_stylesheet_directory_uri() . "/assets/js/ajax.js", array('jquery'));
    //the_ajax_script will use to print admin-ajaxurl in custom ajax.js
    wp_localize_script('my-ajax-handle', 'the_ajax_script', array(
        'ajaxurl' => admin_url('admin-ajax.php'), '_nonce' => wp_create_nonce('my-ajax-handle-nonce')
    ));
}

add_action("wp_enqueue_scripts", "js_enqueue_scripts");

After that you can add the following to functions.php, this will be used for frontend ajax requests. nopriv isnt needed for admin requests.

add_action('wp_ajax_nopriv_load_more_post_ajax', 'load_more_post_ajax');
add_action('wp_ajax_load_more_post_ajax', 'load_more_post_ajax');

The above part is the unique identifier for your ajax function, and where the data must be sent to get processed and return the response from.

Next lets build the php function to process the request we just asked for:

    /**
     * Load more posts using ajax.
     */
    function load_more_post_ajax() {

        if (wp_verify_nonce($_REQUEST['security'], 'my-ajax-handle-nonce') === false) {
            wp_send_json_error();
            wp_die('Invalid Request!');
        }

        $ppp = $_POST['ppp'] ?? 1;
        $page = $_POST['pageNumber'] ?? 0;

        $loop = new \WP_Query([
            'suppress_filters' => true, 'post_type' => 'post', 'posts_per_page' => $ppp, 'paged' => $page,
        ]);

        if ($loop->have_posts()) {
            while ($loop->have_posts()) : $loop->the_post();
                echo "<div><h1>' . get_the_title() . '</h1>' . get_the_content() . '</div>";
            endwhile;
        }
        wp_reset_postdata();
        wp_die(); // This must always be here, this will close to process.
    }

And lastly we will create the JQuery in our new file ajax.js:

jQuery(document).ready(function () {
    jQuery('#load-more').on('click', function () { //Use on operator for dom loading ease
        var $this = jQuery(this); // This is the button object
        var data = {}; // Create an Object to add variables to later if we change them
        data.action = 'load_more_post_ajax'; // Refer to action
        data.page = 2; //Add whatever else you want
        data.security = the_ajax_script._nonce;

        $this.html('Loading...'); // Change the wording on click.

        jQuery.ajax({
            url: the_ajax_script.ajaxurl,
            type: 'post',
            data: data,
            success: function (response) {
                $this.html('Load More'); // Change the wording back on success.
                if (response !== '') {
                    $('.testimonials').append(response);
                    page++;
                } else {
                    $('.load-more-posts').hide();
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
            }
        });
    });
});

you can play around with these options, the possibilities are endless.

发布评论

评论列表(0)

  1. 暂无评论