I’m trying to integrate ajax in wordpress using the wp codex guidelines.
In the PHP I added:
wp_enqueue_script ( 'my_ajax', ADMIN_URL . 'js/ajax.js','jquery','1.0.0' );
wp_localize_script( 'my_ajax', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
The ajax code is:
jQuery.ajax({url: MyAjax.ajaxurl, type: "POST",data: {action: 'myaction',postID : MyAjax.postID}, success: function(response) {
alert('Got this from the server: ' + response);
}});
and the PHP function that should be called by ajax is:
function ajax_function() {
...do something...
}
add_action('wp_ajax_myaction', 'ajax_function');
add_action('wp_ajax_admin_myaction', 'ajax_function');
The ajax call is successful (the “alert” works), however, the php function “ajax_function” is never called.
After doing some debugging I realized that even though the action call add_action(‘wp_ajax_ sets a new element in the global $wp_filter array, when the corresponding do_action runs inside admin-ajax.php, the $wp_filter array no longer contains that element.
Therefore, “ajax_function” function is ignored.
Any idea why the function is not called?
In my projects I do it like that
PHP
Javascript
Please follow the code:
and in your ajax call do this:
in the ajax call you’ll call your function without
prefix_ajax_
. Only call by it’s remaining. In that case it’sadd_myfunc
. In the response it will senddone
if everything goes right. Else response will be0
or-1
.Hope it will help. Thank you.