Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Why a strange discrepency between get_current_user_id() when using AJAX versus output of document.cookie?

I had to trace through WordPress core and the REST API plugin code to fix this, but finally did it. The solution is described here.

The TL;DR of the solution is that the WP-API will ignore the content of the login cookie and assume an unauthenticated (logged out) request unless the correct value is given in the _wpnonce HTTP GET parameter (in the query string) or the HTTP_X_WP_NONCE HTTP header. My JavaScript did not correctly include this. The corrected JavaScript method looks like this:

/**     
 * Checks for any new comments.
 */     
var pollForNewComments = function () {
    var url = api_base + '/comments&post=" + getPostId() + "&offset=" + getCommentCount()
        + "&_wpnonce=" + wpApiSettings.nonce;
    jQuery.get(url, function (response) {
        if (response.length) {
            appendComments(response);
            showNewCommentsNotice();
        }
    });
};

Note that adding the _wpnonce parameter in the query string with the wpApiSettings.nonce global JavaScript variable (which is added by the REST API plugin) fixes the issue for me.

Related Posts:

  1. wp_set_auth_cookie() doesn’t work in Ajax call
  2. WordPress Ajax Login without page reload
  3. Ajax login fails: script sets cookies, but is_user_logged_in() returns false
  4. WordPress AJAX Login Screen
  5. Detecting post type within init action
  6. Ajax form submission from admin panel
  7. WordPress Nonce Issue for Ajax Login and Logout
  8. How can I automatically login using a URL?
  9. How to securely add an Ajax button to a WP Admin page?
  10. wp_remote_get() to get AJAX url /wp-admin/admin-ajax.php
  11. how to use reCaptcha v3 in wordpress custom login form?
  12. WP-API and Basic Auth returning 403 on POST but not GET
  13. AJAX requests broken due to HTTPS for wp-admin
  14. Extending wp JavaScript base class to make a post request to a custom REST endpoint
  15. wp-admin AJAX with Fetch API is done without user
  16. How to add WP API and JS featured image attachment
  17. Is it safe to manually sign a user in using AJAX?
  18. Woocommerce Ajax Add cart not working
  19. WP Admin AJAX Security – using POST to include a relative URL
  20. WordPress Ajax Not Working ( Custom Admin page)
  21. SSO autologin WordPress + Ajax
  22. Pass additional parameter with async upload
  23. How can I set cookies on both secure and non-secure origins at the same time?
  24. Cookie Domain is preventing Admin login
  25. Ajax login without redirect/reload
  26. Use WP admin AJAX url to hide API key
  27. Interim-Login form on frontend
  28. Custom Login with Ajax not working with IE
  29. post values to custom post type which has advanced custom fields
  30. Preprocess submitted data
  31. How to check nonce lifetime value of plugins?
  32. What WP-API authentication method should I use to interact with anonymous / not-logged visitors?
  33. Use AJAX in a WordPress Plugin to Get Data From Custom Database?
  34. admin-ajax.php returns 0 even when the post status code is 200 OK
  35. Can I use application/json content type in WordPress
  36. jQuery.post returns 0
  37. Login issue with subdomain installs
  38. WordPress Admin login redirect to homepage
  39. wordpress admin ajax trash_comment
  40. WordPress custom ajax login not working on mobile browsers
  41. Ajax call not working anymore
  42. WorddPress website admin part not working correctly – I think ajax/json issue
  43. Why does WordPress use cookies for /wp-admin and /wp-content/plugins for non-admin users [duplicate]
  44. Should I edit a user meta field with PUT, PATCH, or POST and WP::Editable
  45. How modify comments metabox on post edit screen in WordPress?
  46. Weird admin-ajax.php problem
  47. WordPress Get Header and Footer using in Admin Area
  48. get_comments() returns empty array if called through AJAX
  49. Why WordPress not logout after I have close my browser?
  50. Caching for logged in user and Ajax update
  51. WordPress blocking polling request when signed into Admin
  52. ERROR: Cookies are blocked due to unexpected output – no access to FTP
  53. PHP cookie not set within AJAX call
  54. randomly get 400 error while user is logged in wp_ajax
  55. How to submit a button automatically after every scheduled hours?
  56. Blocking admin-ajax.php from outside domain
  57. wp-admin/admin-ajax.php 400 Bad request (chrome console)
  58. contact form 7 form not working in admin panel
  59. How does the security of admin_ajax.php work?
  60. Using Ajax with a Class file
  61. Displaying PHP Errors from admin-ajax.php
  62. Adding “Remember Me” in custom login
  63. Stop admin-ajax?
  64. Is it safe to assume that a nonce may be validated more than once?
  65. store/cache ajax sent data to avoid repeated request
  66. Run again current query via ajax but changing a var
  67. Quick Edit: Selected Custom Taxonomy Not Refreshing After Save
  68. wp_verify_nonce always returns false when logged in as admin
  69. Constructing a custom login form using ajax
  70. How to check an ajax nonce in PHP
  71. Admin username and password
  72. admin-ajax.php slows down, but cant figure out which plugin
  73. Convert this relative path to absolute
  74. Load WP content with ajax less server demanding and faster than normal page loading?
  75. Admin-ajax.php 400 error
  76. eventON plugin AJAX call triggers website crash
  77. Ajaxify Form That Submits To Same Page To Display Post Data [closed]
  78. Change header.php after ajax call
  79. Retrieve JSON file from JS trough php
  80. Using admin-ajax prevents regular php form submission
  81. Sql formatting for post data within function
  82. Send checkbox status with Ajax / JSON and save it
  83. ajax refresh to display new posts
  84. wp ajax execution time aborted 30 sec
  85. What is the relationship between UFW (firewall) being enabled and cron job running?
  86. WPBakery post content inside Bootstrap Modal
  87. Hook after all metadata are set is triggering several time
  88. check_ajax_reffer not working when logged
  89. Ajax show custom post data form & script
  90. Portfolio list view after clicking back button
  91. Default and warning messages & no login
  92. Admin Login Checks
  93. AJAX save options inside class
  94. How to test if in dashboard, bypassing Ajax quirk
  95. Usage of wp_send_json_success and wp_redirect at the same time
  96. Can I make an ajax response cross-domain?
  97. update_user_meta updates to a wrong ID
  98. WordPress sound bell when new data will add
  99. Impossible User Registration
  100. Can a scrollable date picker be done in WordPress for archives?
Categories ajax Tags ajax, cookies, login, wp-admin, wp-api
wp_add_inline_style() not working?
Delete transients in website

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress