I am trying to make an AJAX call to a PHP file on a different site:
$.ajax({
type: "GET",
dataType: "json",
url: 'http://user:password@www.myurl.com/myphpfile.php',
data: {
records: JSON.stringify(workingarray),
account: account,
},
complete: function(response) {
var parsedresponse = $.parseJSON(JSON.stringify(response)).responseText.split("<br>");
otherFunction(parsedresponse);
}
});
My PHP file:
<?php
header('Access-Control-Allow-Origin: *');
header('content-type: application/json; charset=utf-8');
$records = json_decode($_GET['records']);
$account = $_GET['account'];
.....[LOGIN AND SQL QUERY].....
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo json_encode($row['Some columns']."<br>", JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
$conn->close();
?>
This all worked great until I noticed I hadn't actually turned on authentication. Once I did that, the whole thing just broke down, and I always get the following error:
XMLHttpRequest cannot load http://user:password@www.myurl.com/myphpfile.php (...) . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://originurl.co.uk' is therefore not allowed access. The response had HTTP status code 401.
As you will see from my PHP code however, there IS a header present. I have also tried adding the following 2 lines to my .htaccess:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Credentials true
With frustratingly little effect, which is to say, no effect whatsoever.
I have attempted to convert the datatype to JSONP, but I am not really sure how to go about doing this... I have tried the following changes:
$.ajax({
type: "GET",
dataType: "jsonp",
url: 'http://user:password@www.myurl.com/myphpfile.php?callback=?',
data: {
records: JSON.stringify(workingarray),
account: account,
},
complete: function(response) {
var parsedresponse = $.parseJSON(JSON.stringify(response)).responseText.split("<br>");
otherFunction(parsedresponse);
}
});
My PHP file:
<?php
header('Access-Control-Allow-Origin: *');
header('content-type: application/jsonp; charset=utf-8');
...
while ($row = $result->fetch_assoc()) {
echo $_GET['callback'] . "(" . json_encode($row['Some columns']."<br>", JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . ")";
}
$conn->close();
?>
This doesn't result in an error in the console as far as I can see, but the only thing I could make sense of in the response was this:
status: 200
statusText: "load"
(I added a console.log(parsedresponse)
line to the complete:
function for debugging purposes, but I must admit I am not entirely sure how to interpret most of what I am seeing.)
Any help or suggestions would be much appreciated because this is causing me a lot of frustration.