07-27-2023, 12:06 PM
I am trying to set a cookie in a wp ajax request handler without any success.<br>Hope someone can help me.<br><br>
Here is client-side code:<br>
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');
Here is client-side code:<br>
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');