I’m using a WordPress code pattern that’s worked for me many times before on client sites, but now that I’m using it my own site, it just won’t work. I’ve been looking at this problem, on and off, for weeks, and I’ve now separated it from my dev site and reconstructed it as a very simplified set of test pages and code in the WordPress twentytwentythree theme. There’s no plugins to mess things up.
Here’s the parent page:
<?php
/*
Template Name: Ajx Test
*/
$tid = 1234;
get_header(); ?>
<div class="content">
<header>
<h1 class="page-title">Ajax Test</h1>
</header>
<div class="ajax-test-target"></div>
</div> <!-- end .content -->
<script>load_test_content(id=<?php echo $tid; ?>);</script>
<?php get_footer(); ?>
The content function (functions/ajax-test-content.php):
<?php
/* Loop Archive Portfolio Ajax */
add_action( 'lr_ajax_test_content', 'test_content' );
add_action( 'lr_ajax_nopriv_test_content', 'test_content' );
function test_content() {
//extract vars incomming from js load_test_content fn
if (!empty($_POST)) {
$windoww = $_POST["win_w"];
echo '$windoww: '.$windoww.'<br>';
$tid = $_POST["t_id"];
echo '$tid: '.$tid.'<br>';
} ?>
<div><p>Hello World</p></div>
<?php
wp_die();
}
Enqueue the script (functions/enqueue-scripts.php):
<?php
function site_scripts() {
global $wp_styles;
// Adding scripts file in the header
wp_enqueue_script( 'lrcustom-js', get_template_directory_uri() . '/assets/scripts/lr-custom.js', array( 'jquery'), $ver = false, $in_footer = false );
wp_localize_script( 'lrcustom-js', 'lr_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', 'site_scripts', 999);
Require the above content and scripts functions (functions.php)
// Register scripts and stylesheets
require_once(get_template_directory().'/functions/enqueue-scripts.php');
// Adds ajax-test-content Ajax Return
require_once(get_template_directory().'/functions/ajax-test-content.php');
The JS:
<script>
var window_w=jQuery(window).width();
// Ajax Test
function load_test_content(id) {
console.log('test_content fires. id='+id);
console.log('Ajax URL:', lr_ajax_object.ajax_url);
console.log('Window Width:', window_w);
console.log('Term ID:', id);
jQuery.ajax({
url: lr_ajax_object.ajax_url,
data: {
'action' : 'test_content',
'win_w' : window_w,
't_id' : id
},
type: 'POST',
success: function(data) {
jQuery(".ajax-test-target").html(data);
console.log("test_content Ajax success");
},
});
}
</script>
Console.log returns:
[Log] test_content fires. id=1234 (lr-custom.js, line 41)
[Log] Ajax URL: – "https://lenrooney.com/wp/wp-admin/admin-ajax.php" (lr-custom.js, line 42)
[Log] Window Width: – 1789 (lr-custom.js, line 43)
[Log] Term ID: – 1234 (lr-custom.js, line 44)
[Error] Failed to load resource: the server responded with a status of 400 (Bad Request) (admin-ajax.php, line 0)
I hope someone out there can help me figure out what’s gone wrong. Thanks!