OiO.lk Blog PHP Ajax not detecting whether client is WordPress Admin/user
PHP

Ajax not detecting whether client is WordPress Admin/user


I have a server side php method that is invoked (ajax/jquery) and needs to output a different result if caller (browser) is logged in as a wordpress admin or just a visitor.

Tried different things, including

  • server side: is_user_logged_in() : does not return true even if admin logged
  • client side : document.body.classList.contains( ‘logged-in’ ) : returns true even if unlogged

Maybe a cookie / WordPress login needed to pass the token ? or other ?

Thoughts ?

Tried several things including :

  • server side: is_user_logged_in() : does not return true even if admin logged
  • client side : document.body.classList.contains( ‘logged-in’ ) : returns true even if unlogged
var form_data = new FormData();

form_data.append('action', 'ajax_custom_request_general');
form_data.append('ajax_request_id', 'getuserinfo' );

jQuery.ajax (
    {
        ajaxurl: 'https://www.example.com/wp-admin/admin-ajax.php',
        url: 'https://www.example.com/wp-admin/admin-ajax.php',
        type: 'post',
        contentType: false,
        processData: false,
        data: form_data,
        success: function (response)
            {
                alert("success"+response+"[end]");

            }, 
        error: function (response)
            {
                alert("error"+response+"[end]");
            }
    }

);
function ajax_custom_request_general()
{
    $result = "";
    if ( isset($_REQUEST) )
    {
        $_field_ajax_request_id = $_REQUEST['ajax_request_id'];
        $_field_ajax_request_id = trim($_field_ajax_request_id);
        $result = "ERR[no request specified]".'='.$_field_ajax_request_id;

        if( $_field_ajax_request_id == 'getuserinfo' )
        {
            if ( is_user_logged_in() ) // DOES NOT WORK
            {
                $result="1";
            }
            else
            {
                $result="0";
            }

            if (isset($_SESSION['user_id'])) // DOES NOT WORK
            {
                $result="1";
            }
            else
            {
                $result="0";
            }
        }

        echo $result;
    }

    // Always die in functions echoing ajax content
    die();
}

add_action( 'wp_ajax_ajax_custom_request_general', 'ajax_custom_request_general' );
add_action( 'wp_ajax_nopriv_ajax_custom_request_general', 'ajax_custom_request_general' );



You need to sign in to view this answers

Exit mobile version