How can I do this JSONP AJAX request the CORS way?
This JSONP AJAX request allows any domain to access a domain and can read the cookies for that domain. What is the exact equivalent for doing it the AJAX CORS way?
JSONP AJAX working example:
// Domain 1 (any domain can do this request to domain 2 and attempt to read cookies)
// JS
$.ajax({
url: 'https://domain2.com/example',
type: "post",
dataType: "jsonp",
success: function(response) {
alert(response);
}
});
// Domain 2
// PHP
// Read a cookie for this domain
$testCookie = $_COOKIE[0];
$callback = $_POST['callback'];
echo $callback . '(' . json_encode($testCookie) . ')';
die();
AJAX with CORS equivalent:
// Domain 1 (I want any domain to be able to do this request to domain 2 and attempt to read cookies)
// JS
$.ajax({
url: url,
crossDomain: true,
xhrFields: {withCredentials: true},
type: "post",
dataType: "json",
success: function(response) {
alert(response);
}
});
// Domain 2
// PHP
// Read a cookie for this domain
$testCookie = $_COOKIE[0];
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 604800');
header("Content-type: application/json");
echo json_encode($testCookie);
die();
This has an error message saying you can't have *
wildcards when using withCredentials: true
, but the withCredentials: true
is needed to read cookies. I can change *
in header('Access-Control-Allow-Origin: *');
to the URL of domain 1, which will work, but how can I get this work so any domain has access like in my jSONP example? From my research, this can't be done, but would this be allowed to work perfectly fine for JSONP AJAX request?