I'm writing a plugin. There is a button, that triggers an ajax-request to an action I added in my plugin page:
Head of my plugin PHP file:
add_action('wp_ajax_update_nav_items', 'update_nav_items' );
add_action('wp_ajax_nopriv_update_nav_items', 'update_nav_items' );
wp_enqueue_script( 'addItemToNav', plugin_dir_url( __FILE__ ) . 'js/navFunctions.js', array( 'jquery', 'json2' ) );
wp_localize_script( 'addItemToNav', 'menuItems', array(
// URL to wp-admin/admin-ajax.php to process the request
'ajaxurl' => admin_url( 'admin-ajax.php' ),
// generate a nonce with a unique ID "myajax-post-comment-nonce"
'postCommentNonce' => wp_create_nonce( 'update_nav_items-nonce' ),
'action' => 'update_nav_items'
)
);
function update_nav_items() {
// Testing stuff
$response = json_encode( array( 'response' => 'success', 'html' => 'some value' ) );
ob_clean();
print_r( $response );
echo json_encode( $response );
die();
}
My JavaScript which triggers:
var data = {
action: 'update_nav_items',
postCommentNonce : menuItems.postCommentNonce,
menuitems: JSON.stringify(itemtest)
};
jQuery.ajax({
url: menuItems.ajaxurl,
data: data,
type: 'post',
dataType: 'json',
success: function( response ) {
console.log(response);
}
});
In the browser console, the request is sent to the correct url, including following parameters:
action update_nav_items
menuitems {"glossary":{"title":"example glossary","GlossDiv":{"title":"S","GlossList":{"GlossEntry":{"ID":"SGML","SortAs":"SGML","GlossTerm":"Standard Generalized Markup Language","Acronym":"SGML","Abbrev":"ISO 8879:1986","GlossDef":{"para":"A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso":["GML","XML"]},"GlossSee":"markup"}}}}}
postCommentNonce 0cee7325b3
(menuitems is just for testing with correct JSON)
What I get as response is 0, so there seems to be a problem with the action. I just don't find it. I already tried adding actions also in my functions.php, it's still not working.
Anyone have a clue?
admin-ajax.php
file directly, placing somevar_dump()
s to determine where the script exits. E.g. it would be helpful to know, whetheradmin_init
get called or not.