最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

php - Cross origin ajax request always returns 0 when calling get_current_user_id();

matteradmin7PV0评论

I currently work on localhost and when I want to test ajax requests to my web server, the function get_current_user_id() always returns 0. When I make the ajax request from my website however, it works. Opening the file in the browser also returns the current wp_user id. The file I make the requests to:

<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php';
echo get_current_user_id();

I have cors in my .htaccess enabled, other WordPress functions work and I get no warnings or errors in my console.

My .htaccess:

<IfModule mod_rewrite.c>
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, 
content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, 
OPTIONS"
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
ErrorDocument 401 /index.php?status=404
ErrorDocument 403 /index.php?status=404
ErrorDocument 404 /index.php?status=404
ErrorDocument 500 /index.php?status=404
</IfModule>

Thanks for any help in advance!

Edit: Due to the answer from "Tim" I tried the following, but it didn't work.

In my functions.php:

function example_ajax_request()
{
    echo get_current_user_id();
    die();
}
add_action('wp_ajax_example_ajax_request', 'example_ajax_request');
add_action('wp_ajax_nopriv_example_ajax_request', 'example_ajax_request');

Javascript on localhost:

var ajax = new XMLHttpRequest();
var formData = new FormData();
formData.append("action", "example_ajax_request");
ajax.open(
  "POST",
  ".php"
);
ajax.onload = function() {
  console.log(ajax.responseText);
};
ajax.send(formData);

---> returns 0 in console as user is not logged in

Update - Found the solution:

Problem was that javascript didn't send cookies automatically cross-domain. I had to set

var ajax = new XMLHttpRequest();
ajax.withCredentials = true;

After that, I had to add

Header add Access-Control-Allow-Credentials true

to my .htaccess, so cross-domain cookie transfer is allowed.

I currently work on localhost and when I want to test ajax requests to my web server, the function get_current_user_id() always returns 0. When I make the ajax request from my website however, it works. Opening the file in the browser also returns the current wp_user id. The file I make the requests to:

<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php';
echo get_current_user_id();

I have cors in my .htaccess enabled, other WordPress functions work and I get no warnings or errors in my console.

My .htaccess:

<IfModule mod_rewrite.c>
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, 
content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, 
OPTIONS"
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
ErrorDocument 401 /index.php?status=404
ErrorDocument 403 /index.php?status=404
ErrorDocument 404 /index.php?status=404
ErrorDocument 500 /index.php?status=404
</IfModule>

Thanks for any help in advance!

Edit: Due to the answer from "Tim" I tried the following, but it didn't work.

In my functions.php:

function example_ajax_request()
{
    echo get_current_user_id();
    die();
}
add_action('wp_ajax_example_ajax_request', 'example_ajax_request');
add_action('wp_ajax_nopriv_example_ajax_request', 'example_ajax_request');

Javascript on localhost:

var ajax = new XMLHttpRequest();
var formData = new FormData();
formData.append("action", "example_ajax_request");
ajax.open(
  "POST",
  "https://my-website/wp-admin/admin-ajax.php"
);
ajax.onload = function() {
  console.log(ajax.responseText);
};
ajax.send(formData);

---> returns 0 in console as user is not logged in

Update - Found the solution:

Problem was that javascript didn't send cookies automatically cross-domain. I had to set

var ajax = new XMLHttpRequest();
ajax.withCredentials = true;

After that, I had to add

Header add Access-Control-Allow-Credentials true

to my .htaccess, so cross-domain cookie transfer is allowed.

Share Improve this question edited Nov 20, 2018 at 2:57 Tim von Känel asked Nov 19, 2018 at 9:35 Tim von KänelTim von Känel 1033 bronze badges
Add a comment  | 

1 Answer 1

Reset to default -1

Don't write your own bootstrapper, use Ajax hooks via wp-admin/admin-ajax.php

Documentation: https://codex.wordpress/AJAX_in_Plugins

Then you can be sure WordPress has included all the functions you need.


Update:

I missed the bit about posting from local machine to remote server. If your JavaScript is running on another domain, it won't be sending back your web server's login cookies. CORS cannot help you with that.

Post a comment

comment list (0)

  1. No comments so far