May 22, 2013

AJAX Cross Domain

Categories: 
Published: 22 May 2013 

Today I came across an issue when trying to load a JSON file via an AJAX call to a subdomain of the site I was working on.

After trying various work around with the JavaScript itself I ended up going in search of solutions.

What I found was the even though I was allowing cross-domain support, and was declaring the data type as JSONP, I was still having issues loading. (It would error on the first: in the JSON).

Eventually, i found a post on Stack Overflow that mentioned something about the issue. Mainly that the AJAX handler in jQuery wasn't accepting that the file I was loading was in fact JSON.

So, I went and added the content type heading into the script that outputs the JSON.
header('Content-Type: application/json; charset=utf8');

Still, no Cigar. However, upon further research, i found I could do all the Cross Domain allowing directly in PHP. This workaround isn't ideal if the JSON is going to multiple hosts, but for a single website pulling in a single data feed and that data feed needs only work for the single website, this workaround works perfectly.

Simply add the Content-Type header:

header('Access-Control-Allow-Origin: http://www.example.com');
header('Access-Control-Max-Age: 3628800');
header('Access-Control-Allow-Methods: GET, POST');

Today I came across an issue when trying to load a JSON file via an AJAX call to a subdomain of the site I was working on.

After trying various work around with the JavaScript itself I ended up going in search of solutions.

What I found was the even though I was allowing cross-domain support, and was declaring the data type as JSONP, I was still having issues loading. (It would error on the first: in the JSON).

Eventually, i found a post on Stack Overflow that mentioned something about the issue. Mainly that the AJAX handler in jQuery wasn't accepting that the file I was loading was in fact JSON.

So, I went and added the content type heading into the script that outputs the JSON.
header('Content-Type: application/json; charset=utf8');

Still, no Cigar. However, upon further research, i found I could do all the Cross Domain allowing directly in PHP. This workaround isn't ideal if the JSON is going to multiple hosts, but for a single website pulling in a single data feed and that data feed needs only work for the single website, this workaround works perfectly.

Simply add the Content-Type header:

header('Access-Control-Allow-Origin: http://www.example.com');
header('Access-Control-Max-Age: 3628800');
header('Access-Control-Allow-Methods: GET, POST');

Ben Maden

Read more posts by Ben
Shares