Problem with cross-site Ajax calls and PHP

Setup

The following example is demonstrating Ajax call made to the weather service.

As long as service calls: http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139l
Ajax is returning success.

Sample Ajax request is presented below:


var jqxhr = $.ajax({

url: “http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139l”,


//url: “http://www.jaskierny.com/playground/json/testJSON.php”,

crossDomain: true,

dataType: “json”,

})

.done(function (data) {

alert(“Success”);

elements = data.weather;

 

$.each(elements, function (index, element) {

alert(element.main);

})

 

})

.fail(function (jqXHR) {

alert(“Error”);


if (jqXHR.status === 0) {

alert(‘Not connect.\n Verify Network.’);

} else
if (jqXHR.status == 404) {

alert(‘Requested page not found. [404]’);

} else
if (jqXHR.status == 500) {

alert(‘Internal Server Error [500].’);

} else
if (exception === ‘parsererror’) {

alert(‘Requested JSON parse failed.’);

} else
if (exception === ‘timeout’) {

alert(‘Time out error.’);

} else
if (exception === ‘abort’) {

alert(‘Ajax request aborted.’);

} else {

alert(‘Uncaught Error.\n’ + jqXHR.responseText);

}

 

});

 

Problem

The problem occurred when I created PHP page, wrapping up an original Ajax call; my Ajax responded with the error, although both requests, from the original site and from my PHP page responded with the identical content:

Original site: http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139l

New PHP page: http://www.jaskierny.com/playground/json/testJSON.php

Here is the source code of my PHP page:

 

<?php

$jsonContent = file_get_contents(“http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&#8221;);

$jsonContent = str_replace(“\n”,”, $jsonContent);

header(‘Content-Type: application/json’);

echo stripslashes(($jsonContent));?>

 

Solution

The problem was related to the access control mechanism, for cross-site HTTP requests. The problem was solved by adding yellow-marked header in the code below:

 

<?php

$jsonContent = file_get_contents(“http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&#8221;);

$jsonContent = str_replace(“\n”,”, $jsonContent);

header(“Access-Control-Allow-Origin: *”);

header(‘Content-Type: application/json’);

echo stripslashes(($jsonContent));?>

 

Additional resources

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS