As you are going to send ajax request from theme (frontend) you need to specify the ajaxurl otherwise it will throw an error “undefined ajaurl”
/**
* frontend ajax requests.
*/
wp_enqueue_script( 'frontend-ajax', JS_DIR_URI . 'frontend-ajax.js', array('jquery'), null, true );
wp_localize_script( 'frontend-ajax', 'frontend_ajax_object',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
)
);
then in your frontend-ajax.js you can can send ajax request like this
$.ajax({
url: frontend_ajax_object.ajaxurl,
type: 'GET',
data: {
action: 'register_action_hook',
},
success: function( response ) {
console.log( response );
},
});
then in your functions.php you can hook your function to the register_action_hook.
add_action( 'wp_ajax_register_action_hook', 'prefix_do_something' );
function prefix_do_something() {
if ( is_user_logged_in ) {
// do something
} else {
// do something else
}
}
you can also use the @Howdy_McGee method to localize the is_logged_in variable using
wp_localize_script( 'handler', 'js_object', $array_of_variables );
and accessing it in your js with js_object.variable_name see the @Howdy_McGee answer for reference.