I know it is being asked a lot. I have followed all solutions but still got the error. What I want is to call PHP function via ajax from admin page on the form submission. This is my code
function myFunction()
{
echo "DONE";
wp_die();
}
add_action('wp_ajax_my_function', 'myFunction);
add_action('wp_ajax_nopriv_my_function', 'myFunction');//i know I don't need this line because I just want to call from admin page
wp_register_script("my_fast_generate_script", my_dir_url . 'assets/js/ajax-my-fast-generate.js', array('jquery'));
wp_localize_script('my_fast_generate_script', 'my_fast_generate_Ajax', array('ajaxurl' => admin_url('admin-ajax.php')));
wp_enqueue_script('my_fast_generate_script');
ajax-my-fast-generate.js
jQuery(function ($) {
$(document).ready(function () {
// id dari button ketika diklik
$('#fast_generate').on('click', function (e) {
e.preventDefault();
console.log("success called until here");
$.ajax({
type: 'POST',
url: my_fast_generate_Ajax.ajaxurl, //diregister di index
dataType: 'json',
data: {
action: 'myFunction',
},
success: function (response) {
console.log("never executed here");
},
error: function (errorThrown) {
console.log(errorThrown);
},
});
});
})
});
As additional info, I used nginx for my web service. I have changed file permissions on the whole WordPress folder to 777, and added .htaccess to my WordPress root directory and the error still occurs.
2
Answers
You have set the
dataType
tojson
which is the data type expected of the server response. but your function just echos"DONE"
and notjson
data, so remove thedataType
. You can also remove thetype
.Actually i think the mistake is in your Javascript. What WordPress expect as the "action" parameter is what stands after the "wp_ajax_" or "wp_ajax_nopriv_", so in your example it should be:
"wp_ajax_my_function", instead in your js you are using "myFunction" which is actually the function name but wordpress doesn’t care about that, it looks into the action name, not the callback which is being used by the action.
So the final JS code should be:
Try it again and let us know