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. I’m trying to register with AJAX
  59. contact form 7 form not working in admin panel
  60. How does the security of admin_ajax.php work?
  61. Nonce verification problem when logging in after a logout
  62. AJAX is not submitting data to database
  63. Ajax call from Plugin using Class
  64. Adding pagination to Ajax Query
  65. Ajax global variable is not getting saved (returns null)
  66. Trigger action via button
  67. Custom login method appears to ignore auth_cookie_expiration
  68. Ajax call on class returns old data
  69. WP admin ajax Pagination issue
  70. enqueue style using admin-ajax.php
  71. How to safely pass post_id and user_id via AJAX to the backend (prevent user from changing it via JS)?
  72. Syntax error on query_vars while handling with Jquery
  73. how to enable ajax on submitting of contact form 7?
  74. wp-login.php entering password nothing happens
  75. Want to send ajax request in wordpress to a custom file in plugin
  76. Can’t get next post info with ajax
  77. On form submitting, admin-ajax.php shows status as pending
  78. Ajax show custom post data form & script
  79. How to inject data content from external json into a modal, using UIkit?
  80. Portfolio list view after clicking back button
  81. How to send the checkbox value to email
  82. WordPress 4.9.6 – IncludeMe & getAjax GET using wrong URL
  83. Ajax by worpdress affects called jquery inside template file
  84. AJAX form not working, still reloads on submit
  85. Create secondary Archive page format?
  86. WordPress Multisite: Login to all subsites at once
  87. Create a post with REST API and adding a category
  88. How to force the admin-ajax.php file to load over HTTPS?
  89. Trying to login to my site redirects me to the first page
  90. Unable to ajax request with meta_query
  91. get_body_class() in ajax envrionment
  92. how to correctly use json_encode with ajax
  93. Get post details with pure javascript ajax
  94. Change button text after ajax db update
  95. Calendar month navigation in Ajax only working once
  96. Call public static method from ajax ‘wpcf7_mail_sent’ hook
  97. 403 error for ajax POST request
  98. how to get password from user instead wp-generate-password
  99. Update user meta via ajax from frontend, saving issue
  100. How to get the admin page slug using wp_loaded hook?
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
  • Post Navigation Elementor
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • WPFacet multiple loop displaying duplicate content
  • Get the name of the template/*html file used
  • Fix: WordPress.DB.PreparedSQL.NotPrepared Plugin Check (PCP)
  • Removing unnecessary CSS and JS code from wp_head()
  • hexagonal image gallery. Am I on the right track? [closed]
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
© 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