How do I set a cookie in a wordpress ajax request handler?

时光毁灭记忆、已成空白 提交于 2020-02-28 05:53:29

问题


I am trying to set a cookie in a wp ajax request handler without any success.
Hope someone can help me.

Here is client-side code:

var foo = $('#foo');
$.ajax({
    url: 'http://127.0.0.1/wordpress/wp-admin/admin-ajax.php',
    type:   'post',
    dataType:   'json',
    cache:  'false',
    data: { 'action' : 'foo', 'foo' : foo.val(), 'nonce' : foo.data('nonce') },
    success: function(data) { console.debug(data) },
    error: function() { console.error('fail') }
});

Here is the plugin:

function foo() {
    check_ajax_referer( 'foo-my-nonce', 'nonce', 'what?!' );

    if (isset($_POST['foo'])) {
        $dir = pathinfo($_SERVER['REQUEST_URI']);
        $dir['dirname'] = $dir['dirname'].'/';
        setcookie('foo', $_POST['foo'], time()+62208000, $dir['dirname'], $_SE    RVER['HTTP_HOST']);

        $output = array('response' => 'success', 'message' => 'have fun');
    }
    else
        $output = array('response' => 'failed', 'message' => 'you are a loser');

    header("Content-type: application/json");
    echo json_encode( $output );
    exit;
 }

 add_action('wp_ajax_nopriv_foo','foo');

回答1:


Ok guys I fixed that. In order to make it working you must set the cookie path to "/" (the root) of the website, instead of the current 'post' or 'dirname':

Instead of:

setcookie('foo', $_POST['foo'], time()+62208000, $dir['dirname'], $_SERVER['HTTP_HOST']);

Use:

setcookie('foo', $_POST['foo'], time()+62208000, '/', $_SERVER['HTTP_HOST']);



来源:https://stackoverflow.com/questions/8357423/how-do-i-set-a-cookie-in-a-wordpress-ajax-request-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!