I'm calling POST on a third-party API that I've been working with via jQuery's $.ajax function. However, when I make the call I get the following error: XMLHttpRequest cannot load http://the-url.com. The request was redirected to 'http://the-url.com/anotherlocation', which is disallowed for cross-origin requests that require preflight.
I saw from this post that this might be a Webkit bug, so I tried it in Firefox (I'm developing in Chrome) and I got the same result.I've tried this on Chrome and Firefox and I get the same result.
Per this post, I also tried using jsonp both by setting the crossDomain
property of the $.ajax function to true
and setting the dataType
to jsonp
. But, this caused a 500 internal server error.
When I start Chrome with the --disable-web-security flag, I don't have any problems. However, if I start the browser normally, then I get the error.
So, I guess this might sort of be a 2-part question. What can I do to make this cross-domain request? If JSONP is the answer, then how do I go about figuring out if the third-party API is set up correctly to support this?
EDIT: Here's the screenshot when I make the call with the browser security disabled: https://drive.google.com/file/d/0Bzo7loNBQcmjUjk5YWNWLXM2SVE/edit?usp=sharing
Here's the screenchost when I make the call with the browser security enabled (like normal): https://drive.google.com/file/d/0Bzo7loNBQcmjam5NQ3BKWUluRE0/edit?usp=sharing
The solution that I came up with was to use cURL (as @waki mentioned), but a slightly modified version that supports SOAP. Then, instead of making the AJAX call to the third party API (which is configured incorrectly) I make the call to my local PHP file which then makes a SOAP call to third party API and passes the data back to my PHP file where I can then process it. This allows me to forget about CORS and all of the complexities associated with it. Here's the code (taken and modified from this question, but without the authentication).
$post_data = "Some xml here";
$soapUrl = "http://yoursite.com/soap.asmx"; // asmx URL of WSDL
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://yoursite.com/SOAPAction",
"Content-length: " . strlen($post_data),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
/* Check for an error when processing the request. */
if(curl_errno($ch) != 0) {
// TODO handle the error
}
curl_close($ch);
// TODO Parse and process the $response variable (returned as XML)