I’m in the process of creating a very simple ajax function, but unfortunately it does not enter the ajax handler function. I’m wondering what is wrong with this code?
Function in functions.php:
function set_favourite_order() {
update_user_meta( 1, 'favorder', 'enterajax' );
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_set_favourite_order', 'set_favourite_order' );
add_action( 'wp_ajax_nopriv_set_favourite_order', 'set_favourite_order' );
Javascript:
jQuery(document).ready(function($){
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
"action": 'set_favourite_order',
"favourite_order" : "test",
"pet_id": 8436
},
success:function(data) {
// This outputs the result of the ajax request
console.log('success');
},
error: function(errorThrown){
console.log(errorThrown);
}
});
} );
The ajaxurl in the javascript is the link to /wp-admin/admin-ajax.php
and running it results in a success message every time.
The problem is that the ajax handler does not run. Any idea what’s wrong? I’ve been trying to debug this for a day.
2
Answers
Please return JSON object in your ajax callback function and use dataType : JSON
In you Js file add dataType.
Always remember that ajaxurl is a variable that stores the admin-ajax.php path and by default wordpress does not provide admin-ajax.php onto the frontend. So you need to initialize it first. There are various way to use, one popurar way is to localize the js.
Here is an another shortest way