Reputation: 183
I know this question has been asked (many times) before but I still can't seem to get it right.
I want to perform an AJAX request in jQuery and get "arbitrary" contents - e.g. it may be html, text, json, img
When I perform something like the following I get the infamous No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mydomain.com' is therefore not allowed access.
$.ajax({
url: "http://www.pureexample.com/jquery/cross-domain-ajax.html",
// dataType: "jsonp",
crossDomain: true,
success: function (data) {
console.log('success');
console.log(data);
},
error: function(request, status, error) {
console.log('Error on request. ' + request.responseText);
alert('Error on request. ' + request.responseText);
}
});
I am not serving the data, so I cannot do anything on the server-side to allow cross domain request. I believe specifying JSONP (commented out) assumes that JSON is being returned? With or without it, it does not work.
So, bottom line - is there a "simple" way to to a cross-domain request so that I may get the result and insert into a tag (e.g. html into a DIV)
Any help, or further explanation is greatly appreciated.
Thanks. Rob
Upvotes: 0
Views: 15415
Reputation: 520
You need to use Ajax-cross-origin a jQuery plugin.
This plugin let you use jQuery.ajax() cross domain.
Use it like this:
$.ajax({
crossOrigin: true,
url: url,
success: function(data) {
console.log(data);
}
});
You can read more here: http://www.ajax-cross-origin.com/
Upvotes: 2
Reputation: 183
Thanks for the responses. Very helpful. I decided to go with a proxy approach for which I found a simple solution here: http://www.paulund.co.uk/make-cross-domain-ajax-calls-with-jquery-and-php
For cut and paste simplicity I've added my code here.
I created a file called crossdomain.html. Included jquery library. Created the following Javascript function:
function requestDataByProxy()
{
var url = "http://UrlYouWantToAcccess.html";
var data = "url=" + url + "¶meters=1¶=2";
$.ajax({
url: "our_domain_url.php",
data: data,
type: "POST",
success: function(data, textStatus, jqXHR){
console.log('Success ' + data);
$('#jsonData').html(data);
},
error: function (jqXHR, textStatus, errorThrown){
console.log('Error ' + jqXHR);
}
});
}
I also added a simple button and pre tag in HTML to load results:
<button onclick="requestDataByProxy()">Request Data By Proxy</button>
<h3>Requsted Data</h3>
<pre id="jsonData"></pre>
And then, the PHP file our_domain_url.php which uses cURL (make sure you have this enabled!)
<?php
//set POST variables
$url = $_POST['url'];
unset($_POST['url']);
$fields_string = "";
//url-ify the data for the POST
foreach($_POST as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
$fields_string = rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($_POST));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
?>
To me, this was a fairly straight-forward solution.
Hope this helps someone else!
Rob
Upvotes: 1
Reputation: 917
I had this very problem a while ago, when using an external webservice to retrieve Brazilian's zip code data (address and such). And I used the very same method you did.
There are a few points that need to be stressed out:
1) Ajax does not allow security protocol differences. That means that, if your page is secured behind a secure protocol (HTTPS), your browser will not allow an external server to return through an unsecured one (HTTP). (I found this late in my development, and the result was to use .NET's webrequest )
2) Setting datatype to "JSONP" doesn't transform a response to JSON. It allows it to be received as such.
3) JSONP is the only datatype acceptd for cross-domain requests. The error message you described is probably due to this reason.
So, to summarize:
When talking about cross-domain requests with ajax,"Arbitrary" contents are restricted to JSON(P). AND the data received MUST be JSON.
Also, until jQuery 1.5, if the response is not correctly typed as JSON, no errors are raised .
I wish I had known these issues before I started my development... Uploading a component to production servers unbeknownst of the fact that requesting data stored within HTTP from SSL-Layered servers is quite an embarassment. ... (Though still quite predictable, actually)
For more info : http://api.jquery.com/jquery.ajax/
Upvotes: 3