$(document).ready(function(){
$.ajaxSetup({
xhrFields: {
withCredentials: true
},
crossDomain: true
});
function user_login(username, password, rememberme){
var request = $.post(
'http://api.example.com/user/login',
{
'username': username,
'password': password,
'rememberme': rememberme
},
'json'
);
request.done(function(res){
...
});
request.fail(function(res){
alert('Request failed. Please try again.');
});
}
});
<?php
/* ALLOW CORS */
$http_origin = $_SERVER['HTTP_ORIGIN']);
$allowed_http_origins = array( "http://other.example.com",
"http://www.example.com",
"http://player.example.com",
"http://app.example.com",
"http://example.com"
);
if(in_array($http_origin, $allowed_http_origins)){
header('Access-Control-Allow-Origin: '. $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
/* RETURN INFO */
$return = array(
'code' => 200,
'text' => 'Succesfully logged in!'
);
echo json_encode($return);
?>
Hello again Stackoverflow,
In my current application I would like to login a user with AJAX on a self written api. This is the current set-up, but I am still getting an error in console:
XMLHttpRequest cannot load http://api.example.com/user/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access.
What can I do to solve this? What is the problem?
Thanks in advance.