admin-ajax.php 403 forbidden only when calling from external file

I am working on some AJAX pagination for my blog. I have everything working correctly when I put the Javascript at the bottom of index.php, but if I move it to my custom.js file that I am enqueuing in my functions.php I get 403 forbidden with the exact same Javascript.

Here’s the working code from index.php:

var ajaxurl = “<?php echo admin_url( ‘admin-ajax.php’ ); ?>”;
var page = 2;
jQuery(function($) {
$(‘body’).on(‘click’, ‘.load-more’, function(e) {
e.preventDefault();
var data = {
‘action’: ‘load_posts_by_ajax’,
‘page’: page,
‘security’: ‘<?php echo wp_create_nonce(“load_more_posts”); ?>’
};

$.post(ajaxurl, data, function(response) {
$(‘.posts’).append(response);
page++;
});
});
});

And here’s the non-working code(403 forbidden) from my custom.js and functions.php I console logged the theme.ajaxurl variable and it is correctly outputting the URL to admin-ajax.php:

custom.js:

var page = 2;
$(‘body’).on(‘click’, ‘.load-more’, function(e) {
e.preventDefault();
var data = {
‘action’: ‘load_posts_by_ajax’,
‘page’: page,
‘security’: ‘<?php echo wp_create_nonce(“load_more_posts”); ?>’
};

$.post(theme.ajaxurl, data, function(response) {
$(‘.posts’).append(response);
page++;
});
});

functions.php:

wp_register_script( ‘custom’, get_template_directory_uri() . ‘/js/custom.js’, array(‘jquery’), ‘1.1’, true);
wp_enqueue_script( ‘custom’ );
wp_localize_script( ‘custom’, ‘theme’, array(
‘ajaxurl’ => admin_url(‘admin-ajax.php’)
));

Anyone know why this would work correctly when placing the javascript directly on the index.php file but not work when trying to call the javascript from a custom enqueued file in functions.php?

Read more here:: admin-ajax.php 403 forbidden only when calling from external file

Leave a Reply

Your email address will not be published. Required fields are marked *