• Following is the plugin’s code:

    <?php
     
    
    require_once ABSPATH . '/wp-includes/formatting.php';
    
    register_activation_hook( file: __FILE__, callback: 'ext_role_menu_activate_plugin' );
    
    register_deactivation_hook( file: __FILE__, callback: 'ext_role_menu_deactivate_plugin' );
    
    register_uninstall_hook( file: __FILE__, callback: 'ext_role_menu_uninstall_plugin' );
    
    function ext_role_menu_activate_plugin() : void
    {
    	$option = getopt( short_options: 'extend_role_menu_plugin' );
    	if ( ! $option ) {
    		add_option( option: 'extend_role_menu_plugin', value: 1 );
    	}
    }
    
    function ext_role_menu_deactivate_plugin()
    {
    	$option = getopt( short_options: 'extend_role_menu_plugin' );
    	if ( $option ) {
    		update_option( option: 'extend_role_menu_plugin', value: 0 );
    	}
    }
    
    function ext_role_menu_uninstall_plugin() : void
    {
    	$option = getopt( short_options: 'extend_role_menu_plugin' );
    	if ( $option ) {
    		delete_option( option: 'extend_role_menu_plugin' );
    	}
    }
    
    // Hook for adding admin menus
    add_action( 'admin_menu', 'rl_add_pages' );
    
    // action function for above hook
    function rl_add_pages() : void
    {
    	add_menu_page( page_title: __( 'Show Roles', 'extend-role-menu' ), menu_title: __( 'Show Roles', 'extend-role-menu' ), capability: 'manage_options', menu_slug: 'show-roles', callback: 'show_roles_func' );
    	 
    	add_submenu_page( parent_slug: 'show-roles', page_title: __( 'Update Role', 'extend-role-menu' ), menu_title: __( 'Update Role', 'extend-role-menu' ), capability: 'manage_options', menu_slug: 'upd-role', callback: 'upd_role_func' );
     
    }
    
    /**
     * Update Role - Capabilities Management Menu.
     *
     */
    
    function upd_role_func() : void
    {
    	if ( ! current_user_can( 'manage_options' ) ) {
    		wp_die( __( 'You do not have the right to have sufficient permissions to access this site.' ) );
    	}
    
    	if (
    		isset( $_POST[ 'role_upd_hidden' ] )
    		&& wp_verify_nonce( $_POST[ 'upd_role' ], 'role_upd_context' )
    	) {
    		if ( wp_roles() ) {
    			$role_match = preg_match( pattern: '/[^a-z0-9_-]+/i', subject: $_POST[ 'upd-role' ] );
    			if ( $role_match == 1 ) {
    				$role       = sanitize_title( $_POST[ 'upd-role' ] );
    				$role       = get_role( role: $role );
    				$capability = sanitize_title( title: $_POST[ 'upd-capability-text' ] );
    				$capability = ( ! ( $role->has_cap( cap: $capability ) ) ) ? '' : $capability;
    
    				if ( $role ) {
    					if ( $capability ) {
    						$role->add_cap( cap: $capability );
    					}
    				}
    			}
    		}
    	}
    	?>
    	<div class="wrap">
    		<form name='role_form_mngmnt' method='post' action="">
    			<input type='hidden' name='role_upd_hidden'
    				value="<?php esc_attr( wp_create_nonce( 'upd_role', 'role_upd_context' ) ) ?>" />
    			<label name="upd-role-lbl" for="upd-role"> Roles </label>
    			<select name="upd-role" id="upd-role">
    				<?php wp_dropdown_roles( selected: 'subscriber' ); ?>
    			</select>
    			<table name="rl_data" id="rl_data">
    				<tr>
    					<th>Capability</th>
    				</tr>
    				<?php
    				$role = 'subscriber';
    				$role = get_role( $role );
    				// var_dump($role);
    			
    				if ( $role ) {
    					$capabilities = $role->capabilities;
    					//var_dump($capabilities);
    					?>
    					<tr id="fill_data">
    						<?php
    						if ( ! empty( $capabilities ) ) {
    							$outp         = '';
    							$arr_cap_keys = array_keys( $capabilities );
    							$arr_cap_vals = array_values( $capabilities );
    							for ( $i = 0; $i < count( value: $arr_cap_keys ); $i++ ) {
    								$outp .= $arr_cap_keys[ $i ] . '->';
    								if ( $i != count( value: $arr_cap_keys ) - 1 ) $outp .= ( $arr_cap_vals[ $i ] == true ) ? ' true, ' : ' false, ';
    								else $outp .= ( $arr_cap_vals[ $i ] == true ) ? ' true ' : ' false ';
    							}
    						}
    				}
    				echo '<td>' . $outp . '</td>';
    				?>
    
    				</tr>
    			</table>
    			<label name="upd-capability-lbl" for="upd-capability-text"> Update Capability </label>
    			<input type="text" value="Choose or Add Capability" name="upd-capability-text" />
    			<input type='submit' value="Add Capability" id="add_capability" onsubmit="checkSubmission();" />
    		</form>
    	</div>
    	<?php
    }
    
    add_action( 'admin_enqueue_scripts', 'my_enqueue' );
    
    function my_enqueue( $hook ) : void
    {
    	// var_dump(value: $hook);
    	if ( 'extend-role-menu.php' !== $hook ) {
    		return;
    	}
    
    	wp_enqueue_script( handle: 'myScripts', src: plugins_url( path: '/js/myScripts.js', plugin: __FILE__ ), deps: array( 'jquery' ), ver: '1.0.0', in_footer: true );
    
    	wp_localize_script( handle: 'myScripts', object_name: 'my_ajax_obj',
    	l10n: array(
    			'ajax_url' => admin_url( 'admin-ajax.php' ),
    			'nonce'    => wp_create_nonce( 'my-extend-role-menu-nonce' ),
    		)
    	);
    }
    ;
    
    add_action( 'wp_ajax_ajax_hundler_hook', 'ajax_handler' );
    
    function ajax_hundler()
    {
    	echo 'bbbbb';
    	$nonce    = check_ajax_referer( 'ajax_hundler_hook', 'my-extend-role-menu-nonce', true );
    	$the_role = get_role( wp_unslash( 'role' ) );
    	if ( $the_role ) {
    		$capabilities = $the_role->capabilities;
    		if ( ! empty( $capabilities ) ) {
    			echo 'aaaa';
    			wp_send_json_success( $capabilities );
    		}
    		return wp_send_json_error( false );
    	}
    }

    And here mySqcripts.js under /js folder:

    jQuery(document).ready(function ($) {
    	$("upd-role").change(function () {
    		var this2 = this;
    		$.post(
    			my_ajax_obj.ajax_url,
    			{
    				_ajax_nonce: my_ajax_obj.nonce,
    				action: "ajax_hundler_hook",
    				title: this2.value
    			}, function (data) {
    				alert('ooo');
    				console.log(data);
    			}
    		);
    	});
    });

    I get response 200 ok but i cannot get the data back on jquery console window. Also many plugins with jquery debugging get confused with the registering hooks… Any suggestion?

Viewing 3 replies - 1 through 3 (of 3 total)
  • It looks like there are some errors and inconsistencies in your PHP and JavaScript code that might be causing issues. I have corrected some of them below.

    In your PHP code:

    1. Replace the ajax_hundler function name with ajax_handler:
    function ajax_handler() {
        // ...
    }
    

    Change the wp_ajax_ajax_hundler_hook action to wp_ajax_ajax_handler_hook:

    add_action( 'wp_ajax_ajax_handler_hook', 'ajax_handler' );
    
    1. In the ajax_handler function, replace wp_unslash( 'role' ) with $_POST['role']:
    $the_role = get_role( $_POST['role'] );
    
    1. Remove the echo 'bbbbb'; line in the ajax_handler function.

    In your JavaScript code (myScripts.js):

    1. Change the $("upd-role") selector to $("#upd-role"):
    $("#upd-role").change(function () {
        // ...
    });
    

    Change the action value in the $.post function to "ajax_handler_hook":

    $.post(
        my_ajax_obj.ajax_url,
        {
            _ajax_nonce: my_ajax_obj.nonce,
            action: "ajax_handler_hook",
            role: this2.value
        }, function (data) {
            // ...
        }
    );
    

    After making these changes, try running your code again and check if the data is being returned properly in the jQuery console window.

    Thread Starter konstantinosdimos

    (@konstantinosdimos)

    jQuery(document).ready(function ($) {
    	alert('ole');
    	$("#upd-role").change(function () {
    		var this2 = this;
    		$.post(
    			my_ajax_obj.ajax_url,
    			{
    				_ajax_nonce: my_ajax_obj.nonce,
    				action: "ajax_handler_hook",
    				role: this2.value
    			}, function (data) {
    				console.log(data);
    				
    			});
    	});
    });

    Changed the code to the above, i cannot even get the alert on document load.

    To find the issue:

    1. Check the browser console (F12) for errors.
    2. Make sure myScripts.js is loaded in the “Network” tab of dev tools.
    3. Confirm jQuery is loaded before your script in the HTML source.
    4. Double-check the ‘my_enqueue’ function in your PHP code.

    If these don’t help, share more info about your setup like the theme, plugins, and custom code.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Ajax Request is not getting response data…’ is closed to new replies.