PHP Tutorial: REST For AJAX
| May 2, 2012 | Posted by Greg Bulmash under PHP |
The other day, at work, I had to cobble together a web service for another team's developer to ping. We set it to be a POST and I tested it with a form that posted the necessary values to it. Everything worked fine.
Then she e-mails and says she can't get the expected response. We go through some stuff related to the fact that it's a POST and we're running it on HTTPS, but none of that works. I ask her if she can send me the code that she's using to access it and she sends me a block of jQuery that posts the form via AJAX.
She says she was expecting a REST interface and I'm wondering if REST doesn't support POST, because I thought it did. A quick bit of research and I find I was right. But I also find out that when an AJAX script is accessing a REST interface across domains, you need to add extra headers on your response that enable CORS (cross origin resource sharing); basically telling the receiving browser that it has permission to access this resource from the site that was calling it.
One such header, Access-Control-Allow-Origin makes it fairly easy. Follow your 200 with an Access-Control-Allow-Origin
header("Status:200 OK");
header("Access-Control-Allow-Origin: http://foo.bar");
If you don't care who is accessing the resource, you can use a wildcard (*) instead of the URL for the allowed domain.
Another option is to access information about the request through the $_SERVER global, make your own determination that it's coming from an acceptable source, and then add the Access-Control-Allow-Origin header only if the request passes your tests.
Recent Comments