There’s two problems:
- You’re not sending the AJAX request to the correct URL.
- You’re using PHP-style concatenation instead of JavaScript.
For the first issue, a relative URL "admin-ajax.php"
is not going to work. If you are on a page like /about-us/
then jQuery is going to send the request to /about-us/admin-ajax.php
, which doesn’t exist.
The most reliable way to set the URL is to get the URL with PHP using the admin_url()
function and use wp_localize_script()
to send the value to your script:
function c4l_custom_script_and_style_includer() {
wp_enqueue_style( 'c4l-css', plugins_url( 'css/c4l-custom-styles.css' , __FILE__ ) );
wp_enqueue_script( 'c4l-js', plugins_url( 'js/c4l-custom-scripts.js' , __FILE__ ) );
wp_localize_script( 'c41-js', 'c41', ['ajaxurl' => admin_url('admin-ajax.php')] );
}
add_action( 'wp_enqueue_scripts', 'c4l_custom_script_and_style_includer' );
What that extra line does is: If the c4l-js
(the first arugment) is enqueued, create a global JS variable called c41
(the second argument) with the keys and values passed to the 3rd argument. We have provided the correct URL to admin-ajax.php.
So now in your script, set the URL to:
url: c41.ajaxurl,
The other issue is how you’re concatenating the response to a string in JavaScript:
alert('ajax result: '.response);
.
is the character used to concatenate strings in PHP, but in JavaScript you need to use +
:
alert('ajax result: ' + response);