I'm using jQuery 1.7.2 and would like to make a POST request to another domain. It must be a POST request. But this does not work in internet explorer (I tried on IE9); it works on all other browsers.
I have this script:
<script>
jQuery.support.cors = true;
jQuery(function() {
$.ajax({
crossDomain : true,
cache: false,
type: 'POST',
url: 'http://someotherdomain/test.php',
data: {},
success: function(da) {
console.log(JSON.stringify(da))
},
error: function(jqxhr) {
console.log('fail')
console.log(JSON.stringify(jqxhr))
},
dataType: 'json'
});
});
</script>
I get back the error:
{"readyState":0,"status":0,"statusText":"Error: Access denied.\r\n"}
My PHP file looks like this:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS');
echo json_decode(array('success' => 'yes'));
Internet Explorer (including IE9) does not support CORS. You have to proxy all your cross-domain request (post to PHP script on the same domain, that reposts with curl your query and returns the response)
To support CORS in IE < 10, you must modify the ajax method to use the XDomainRequest object. This plugin does it for you: https://github.com/jaubourg/ajaxHooks
Your script looks correct but I believe you need to change:
header('Access-Control-Allow-Origin: *');
to
header('Access-Control-Allow-Origin: x-requested-with');
or
header('Access-Control-Allow-Origin: {Origin}');
Where {Origin} is the value of the Origin header. It's my understanding that just putting '*' won't work if an Origin has been given.
Also, IE8 and IE9 have limited support for this but it does work if you put jQuery.support.cors = true
, as you've done.
This works in IE9.
<!DOCTYPE html>
<head>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
var url = "http://msdn.microsoft.com/en-us/library/windows/desktop/ms759148(v=vs.85).aspx";
function getRequest() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {alert("Error while getting 6.0");}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {alert("Error while getting 3.0");}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {alert("Error while getting 2.0");}
throw new Error("This browser does not support XMLHttpRequest.");
};
var request = getRequest();
request.open("POST", url, false);
request.send();
alert("Content from :"+url+":"+ request.responseText);
</script>
</head>
<h1>AJAX ActiveX</h1>