I am currently attempting to retrieve data from a REST service I created with PHP/Slim. The service retrieves data from the database fine, however when I try to get this data through an AJAX call I am faced with a 401 Unauthorized Error.
Originally console was saying it was due to not having an Access-Control-Allow-Origin
parameter set, but this was fixed by adding the parameter into web.config
(IIS) - Now I am just left with GET http://localhost:8081/api/v1/users 401 (Unauthorized)
logged in the Chrome console.
The call is intended to be hosted on a different server, so for testing I have put the site onto port :8082
with the RESTful service on :8081
.
My AJAX call is written as follows (I have also tried jsonp
but due to URL Rewrite the ?callback=...
throws a 404 error).
$.ajax({
type: 'get',
url: 'http://localhost:8081/api/v1/users',
dataType: 'json',
success: function(data) {
console.log(data);
}
});
My RESTful service is written as follows:
header('Content-Type: application/json');
// Load the Slim framework
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
// Create a new Slim object
$app = new Slim\Slim();
// Define RESTful actions
$app->get('/users', function() { get("SELECT * FROM users"); });
function get($sql) {
try {
$db = getConnection();
$stmt = $db->query($sql);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '{' . json_encode($results) . '}';
}
catch (PDOException $e) {
echo '{"Error": {"Text": ' . $e->getMessage() . '}}';
}
}
[...]