“No ‘Access-Control-Allow-Origin’ header is present” error

When trying to create API endpoints in PHP you might get an error message like this if you’re trying to access it from you development environment or a different machine:

XMLHttpRequest cannot load http://xxxxxx.com/yourpage.php. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://xxxrequestoriginxxx.com’ is therefore not allowed access.

Sounds complicated but the fix is usually simple, just add the following at the start of your php code:

<?php
header("Access-Control-Allow-Origin: *");

// All the rest of your code

?>

Scraping the IKEA API in PHP

IKEA’s BILLY bookcase 80x28x106cm in birch veneer. A design classic. £45 for the everyman’s unobtrusive storage solution. Over 40 million BILLY bookcases sold since they were created in 1979. But how many of them are there in the my local branch of IKEA at the moment?

billy-bookcase

Not the most important question in the world but a useful one to do a quick demo of how to automatically pull data out of an API in PHP at a regular interval and store it in a database (MySQL in this case) – something that we commonly want to do to compile data-sets where live data readings are provided but historical data is not.

Where is my data?

The first thing to know is where we can get our live data. In the case of the IKEA website, there is a live stock check in the right hand column where you can select a particular store and see availability for the selected product. Here’s the location of the birch veneer BILLY bookcase on IKEA’s website: http://www.ikea.com/gb/en/catalog/products/80279786/. Note that final 8 digit number – that’s our unique product ID.
…click here to read the rest…

A Super-Simple API Proxy for Angular with PHP

Often in an Angular JS web application (or any other front-end framework) we want to make a call to an API which needs to be authenticated with an API key (a unique code assigned to us by the API provider) using the $http service. We want to keep our API key secret and so don’t want to put in our .js files where it can be viewed, and then used, by anyone but JavaScript is all on the client-side so how do we keep our key safe?

…click here to read the rest…