i have simple wordpress form to add data in custom table in wordpress using Ajax

my Ajax code

jQuery.ajax(ajax_object.ajax_url, {
    type: "POST",
    data: data,
    cache: false,
    success: function (response) {
        alert(response);

    },
    error: function (error) {
        if (typeof console === "object") {
            console.log(error);
        }
    },
    complete: function () {
    }
});

my php code to save data

 if (!class_exists('bookly_appo_Ajax')) {
    class bookly_appo_Ajax
    {
        public function __construct()
        {
            add_action('init', array(&$this, 'init'));
        }

        public function init()
        {
            add_action('wp_enqueue_scripts', 'enqueue_ajax_booklyapp');
            function enqueue_ajax_booklyapp($hook)
            {

                wp_enqueue_script('ajax-script-booklyapp', plugins_url('/ajax.js?v=' . rand(), __FILE__), array('jquery'));
                wp_localize_script('ajax-script-booklyapp', 'ajax_object',
                    array(
                        'ajax_url' => admin_url('admin-ajax.php')
                    )
                );
            }

            add_action('wp_ajax_add_category_bookly', 'add_category_bookly_callback');
            function add_category_bookly_callback()
            {
                $storeid = $_REQUEST['storeid'];

                $rows = $wpdb->insert(
                    $table_category, array(

                        'store_id' => $storeid,
                    )
                );
                $lastid = $wpdb->insert_id;
            }
        }
    }
}

my question is

  1. when login with admin my ajax work fine but when login with other user(subscriber user) of my site it’s give error “Opps!You do not have sufficient perissions to access this
    page”
  2. which type of accessibility provide to subscriber to used admin-ajax.php file

1 Answer
1

For non-admin users to be able to use an ajax function, you need to also include a second hook using wp_ajax_nopriv

So right after this:

add_action('wp_ajax_add_category_bookly', 'add_category_bookly_callback');

you should include this:

add_action('wp_ajax_nopriv_add_category_bookly', 'add_category_bookly_callback');

Leave a Reply

Your email address will not be published. Required fields are marked *