Support » Developing with WordPress » Getting 403 error on ajax infinite loading script

  • I’m trying to implement an infinite loading script to my page. However, when the script triggers, I get a 403 – forbidden error. This is my javascript:

    jQuery(document).ready(function( $ ){
    
        var ajaxurl = "<?php echo admin_url('admin-ajax.php') ?>";
        var page = 2;
    
        $(window).scroll(function() {
            if($(window).scrollTop() == $(document).height() - $(window).height()) {
                var data = {
                    'action': 'load_posts_by_ajax',
                    'page': page,
                    'security': '<?php echo wp_create_nonce("load_more_posts"); ?>'
                };
    
                $.post(ajaxurl, data, function(response) {
                    $('.main').append(response);
                    page++;
                });
            }
        });
    
    });

    and this is what’s in my functions.php:

    add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback');
    add_action('wp_ajax_nonpriv_load_posts_by_ajax', 'load_posts_by_ajax_callback');
    
    function load_posts_by_ajax_callback() {
        check_ajax_referer('load_more_posts', 'security');
    
        $paged = $_POST['page'];
        $args = [
            'post_type' => 'spell',
            'posts_per_page' => '30',
            'paged' => $paged
        ];
    
        $my_posts = new WP_Query ($args);
    
        while($my_posts->have_posts()) {
    
            //the content goes here
    
        }
    
        wp_die();
    
    }

    This is the error message on my console log.

    I have double checked and everything seems fine, but I keep getting 403 errors. The initial query, before the script, goes through without any problems.

    The only third party plugin I have installed is Advanced Custom Fields.

    I tried removing the nonce request, but get the same problem.

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Check you .htaccess file for a rule that might limit access to /wp-admin/. Such a rule is often added for security reasons. That’s OK to do, but admin-ajax.php (and sometimes admin-post.php) must be excluded from that restriction.

    If you have no added security measures on your site, your host might be running modSecurity on the server. Ask your host to allow requests to admin-ajax.php.

Viewing 1 replies (of 1 total)
  • The topic ‘Getting 403 error on ajax infinite loading script’ is closed to new replies.