The main problem with your Ajax call is that there are two options (locations) for these ajax calls in Wordpress (and usually in any CMS):
- Admin area calls.
- Front-end calls.
So if your Ajax call is from front-end thus anybody can use that request then you should use this version of adding an action in your functions.php file:
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
so 'wp_ajax_my_function'
will not work on front-end usage. WP will not find your PHP callback function for the Ajax call.
The second I would like to bring your attention to is the important part of the Ajax call which is the target URL:
url: ajaxurl // always defined...
I have seen this at many places and it is a bit misleading people that ajaxurl
is always defined since... version... It is only true for admin Ajax calls again. For front-end Ajax calls you should define the target url yourself. That is true that it is always targeting admin-ajax.php
, but still we have to define that in our javascript for ourself.
The working sample jQuery Ajax call:
// custom jQuery script sample for GET request
jQuery(document).ready(function($) {
const myScript = {
ajax_url : "/wp-admin\/admin-ajax.php"
}
// This is the variable we are passing via AJAX
let fruit = 'Banana';
// This does the ajax request (The Call).
$.ajax({
url: myScript.ajax_url, // we define the target url for ourselves
data: {
'action':'example_ajax_request', // This is our PHP function below
'fruit' : fruit // This is the variable we are sending via AJAX
},
success: function(data, response) {
// This outputs the result of the ajax request (The Callback)
window.alert(data);
console.table(data, response);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
});
And I just a little bit corrected your PHP function where I separated the GET request and the POST request for different responses (and I will create an Ajax POST request to this same function below in my post.
(in functions.php)
<?php
// example ajax call_user_func
// for Ajax GET and POST request
function example_ajax_request() {
if ( $_SERVER['REQUEST_METHOD'] === 'GET' ) {
$fruit = $_REQUEST['fruit'];
// Processes the fruit variable into an Apple
if ( $fruit === 'Banana' ) {
$fruit = 'Apple';
echo json_encode(['fruit' => $fruit]);
} else {
$fruit = 'Kiwi';
echo json_encode(['fruit' => $fruit]);
}
return true;
}
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
// getting the body data from post request
$request_body = json_decode(file_get_contents('php://input'));
$fruit = $request_body->fruit;
if ($fruit === 'Banana') {
$fruit = 'Lemon';
}
return wp_send_json( $fruit, $status_code = null, 0 ) ;
}
}
// add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' ); // if your ajax call is in admin
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' ); // if your ajax call is in front-end
And finally I created an Ajax POST request to the same PHP function with using vanilla javascript (I like it much more than jQuery...):
window.addEventListener('load', async function ajaxTesting(ev) {
let fruit = 'Banana';
const data = {
'action':'example_ajax_request',
'fruit' : fruit
}
const ajax_url_post = "/wp-admin\/admin-ajax.php?action=" + data.action;
try {
const response = await fetch(ajax_url_post, {
method: "POST",
body: JSON.stringify(data),
});
console.log("call was successful", response);
console.log("call was successful", data);
} catch (error) {
console.error(`this call had an error: ${error.message}`);
}
});
You can see above that for post request I defined the target URL a bit differently. The above functions are tested and working in Wordpress 6.2
I hope this will help you in creating working ajax functions in Wordpress.
data
anderrorThrown
so one of those is an object. Try to useconsole.log
instead ofwindow.alert