Reputation: 3064
I am developing a WordPress plugin and trying to use wp_ajax
inside it.
This is my code:
function register_role_category_access() {
wp_enqueue_script( 'role_category_access', plugin_dir_url( __FILE__ ) . 'js/category-restrict.js', array( 'jquery' ), '1.0.0', true );
wp_localize_script( 'role_category_access', 'category_access_ajax_url', array(
'url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'role_access_nonce' )
) );
}
add_action( 'admin_enqueue_scripts', array( $this, 'register_role_category_access' ) );
function update_role_category_access() {
$user_role = isset( $_POST[ 'user_role' ] ) ? $_POST[ 'user_role' ] : 'Not defined';
$selected_cats = isset( $_POST[ 'selected_cats' ] ) ? $_POST[ 'selected_cats' ] : 'None selected';
echo "Chosen role: " . $user_role . ' and categories are ' . $selected_cats;
die();
}
add_action( 'wp_ajax_category_access', array( $this, 'update_role_category_access' ) );
Since the above action could only be done from admin panel I am not using wp_ajax_nopriv_*
hook.
JavaScript file content (category-restrict.js
):
function updateAccess( obj ) {
var selectedCatIds = "";
var accessBox = jQuery( obj ).closest( '.access-box' );
var roleSlug = jQuery( accessBox ).find(".hidden_role").attr("value");
var catList = jQuery( obj ).closest( '.access-box' ).find( '.category-list' );
jQuery( catList ).children().each( function() {
if( jQuery(this).is(":checked") ) {
selectedCatIds += jQuery(this).val() + ",";
}
});
var idLen = selectedCatIds.length;
if( idLen > 0 ) {
selectedCatIds = selectedCatIds.substring(0, idLen - 1);
}
jQuery.ajax({
type: 'POST',
url: category_access_ajax_url, //wp_localize_script: 844
data: {
action: 'category_access', //wp_ajax_category_access: 71
user_role: roleSlug,
selected_cats: selectedCatIds,
},
success: function( result ) {
alert( result );
}
});
}
But when I am calling the script I am getting the following error in console:
http://album.multibaselocal.com/wp-admin/[object%20Object]
404 (Not Found)
I looked into this, but was not able to understand what wrong I have done since my knowledge in WordPress is still limited.
Upvotes: 1
Views: 3976
Reputation: 3948
Your url
param in the AJAX call is wrong. category_access_ajax_url
is a JS object that contains url
and nonce
so your code should be something like this:
jQuery.ajax({
type: 'POST',
url: category_access_ajax_url.url, // access the url property inside category_access_ajax_url
data: {
action: 'category_access',
user_role: roleSlug,
selected_cats: selectedCatIds,
},
success: function( result ) {
alert( result );
}
});
I suggest renaming category_access_ajax_url
to category_access_ajax
to avoid confusion.
Update: You don't really need category_access_ajax_url.url
because WordPress defines a global variable called ajaxurl
in the admin area that you can use for this purpose.
Upvotes: 3