Cross domain jQuery $.ajax request fails for PUT (Method PUT is not allowed by Access-Control-Allow-Methods.)

Horen picture Horen · Jul 17, 2013 · Viewed 8.5k times · Source

I am doing cross domain requests via jQuery's $.ajax to access a RESTful PHP API.
In order to do so I have set the following headers in PHP:

header("HTTP/1.1 $code $status");
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT');

Using the types GET and POST works without problems. However when I do a PUT ajax call Firefox fails completely and shows OPTIONS api.php in the network tab of Firebug.
In Chrome the same thing happens first (OPTION request fails with message Method PUT is not allowed by Access-Control-Allow-Methods.) but Chrome follows up with the actual PUT request that actually works then.

What is the reason for this behaviour?

Answer

Horen picture Horen · Jul 17, 2013

Apparently the browser first sends an OPTIONS request to find out if PUT (or DELETE) requests are allowed.
Since I had not allowed the OPTIONS method in Access-Control-Allow-Methods it failed and so did the PUT request after in Firefox.
Adding OPTIONS to Access-Control-Allow-Methods solved the problem:

header('Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS');