Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 595
Horen Avatar asked Jul 17 '13 14:07

Horen


1 Answers

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');
like image 108
Horen Avatar answered Oct 28 '22 21:10

Horen