var url = "/example/somelink";
jQuery.get( url, params, callback); //works fine
var url = "http://www.yahoo.com";
jQuery.get( url, params, callback); //fails!
when I give the full URL of a site, get() fails...any idea why this is happening?
Thanks
You can't access a remote domain like this, only your own domain. The difference is the domain, not the full vs relative URL.
It's the same origin policy that's blocking you here, you have to use JSONP to get data directly or proxy the request through your own domain.
If by "fails", you mean that you're unable to access the HTML you hoped to receive, this is prevented by the browser for security reasons.
You can manipulate the response only if it comes from the same domain from which the request is sent.
Related
My Javascript file generates a JSON and there are some necessary values which I want to send it to the link www.leaderpush.com/Send/Getjson?Endpoint=endpoint&P256dh=p256dh&Auth=auth
var obj = JSON.parse(t);
var endpoint = obj.endpoint;
var p256dh = obj.keys.p256dh;
var auth = obj.keys.auth;
But I cannot send it to another domain. When I try, the URL that is sent becomes www.AnyDomain.com/www.leaderpush.com/Send...
What is your suggestion?
You need to format the URL correctly.
url = "//www.leaderpush.com/Send/Getjson?Endpoint=endpoint&P256dh=p256dh&Auth=auth";
You need // at the beginning to indicate that the domain name of the URL follows, otherwise it's treated as a filename relative to the current URL.
BTW, this still might not work if the other domain prohibits CORS. You may need to make the request from your server rather than from the client.
Since you have not mentioned the protocol absolutely(HTTP / HTTPS) or relatively(//) in the request URL, the browser treats it as a path and appends the request URL after the origin domain. And the request domain does not seem to support and have valid HTTPS certificate and hence make sure your origin domain is HTTP and the request domain (//www.leaderpush.com) is CORS supported.
Note: Try including crossDomain: true in $.ajax() request header, in case the target server might serve on request to enable cross domain to the client.
Is there a way to get response headers of an iframe onload?
I have already googled it, but really I could not find something useful about it!
Not really. If the iframe is on the same domain you can access its document object which contains some useful information such as document.referrer, but you cannot intercept the full HTTP headers without making an Ajax request for the URL. This would mean requesting the URL again. e.g:
$.ajax( { url: $(#myFrame).attr('src'), success: function(r,x){
console.log( x.getResponseHeader('SomeHeader') );
} } );
This will only work if the iframe src is in the same domain as the calling script.
If you have control on the loaded iframe resource you can dump the header content on a postMessage request to the main window.
Here is the error message:
XMLHttpRequest cannot load (the url1). Origin http://localhost:8081 is not allowed by Access-Control-Allow-Origin.
Here is the code:
$.ajax({
url: (the url2),
async : false,
data: { fbId : eh,
fbSecret : meh,
key : bleh
},
datatype: "json",
success: function(result){
console.log(result);
}
});
I know the url is correct because when I click it it gives me the data I need, which is like {"names" : ["blah"]}
Do I need to give out any more details?
I've tried various things like using jsonp/html instead of json, putting data directly into the url instead of separately as data, and using $.get instead of $.ajax, along with editing $.ajaxsetup....
the error message says it all, you cannot make cross domain ajax requests (exception in case of jsonp but that also has to be supported by the server) due to same-origin-policy
this may help you here http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-cross-domain-ajax-request-with-yql-and-jquery/
ports mismatch ;) the page that tries to establish the request has to be on the same port ;)
I think you are trying to access a server different than the one you served the script from - the JavaScript code inside a page served from server A can access only server A using XmlHttpRequest.
If this is the problem there is no easy solution - you have to use proxy or avoid XmlHttpRequest altogether.
same-origin-policy is a browser security measure that restricts JavaScript code from talking with resources originating from other websites i.e resources loaded from any other domain and/or port. eg. JS running in a web page on http://google.com:80 cannot interact with data loaded from http://cbs.com or even http://cbs.com:8081
Working around SOP
a) Proxy in your server: you create a end point in your app that talks to the external url and returns the result
b) Load the JSON response into a <script> tag otherwise jsonp i.e json with padding
eg:
var url = "http://localhost:8081/?queryString=asdsa&callback=jsonCallback";
var script = document.createElement("script");
script.setAttribute("src", url);
script.setAttribute("type", "text/javascript");
window.jsonCallback = function(jsonObj) {
// use JSON object here
// cleanup
document.body.removeChild(script);
delete window[callback];
}
document.body.appendChild(script)
In your case since you are running it of a different port it is not valid and hence the error thrown by the browser..
and there are some server side changes that go along with this.. read up on how to do it for your scripting language..
basically the response should be something like:
jsonCallback({"Name": "Random", "Id" : 2432, "Rank": 453})
Use dataType: "JSONP" to overcome the limitation you encountered; check out the documentation to implement it correctly. You also have to provide a callback function for it.
The jQuery ajax script below doesn't work on my site if url is without www. I checked Firebug and it doesn't send the ajax call.
$.ajax(
{
type: "POST",
url: "http://www.mysite.com/beta/products.php",
data: "page_type=index&sort=relevancerank&CartId=<?php echo $CartId;?>&HMAC=<?php echo $HMAC;?>",
success: function(msg)
{
$('#content-holder').html(msg);
},
error: function()
{
alert("An error occurred while updating. Try again in a while");
}
});
I'm assuming the calling document URL is referenced as "mysite.com", or "subdomain.mysite.com"? The XMLHttpRequest object (the engine that powers jQuery Ajax calls) can not perform "cross-domain" requests. A subdomain (e.g. 'www') qualifies. Make sure your requests are to the same subdomain.
You don't need to provide an absolute URL, you can simply provide a relative one, and it will work regardless if the your page is loaded with the www. subdomain or not:
//...
type: "POST",
url: "/beta/products.php",
//...
Is your server redirecting to the "www" domain possibly? This is probably just the same-origin policy preventing your outer page from accessing a different domain.
www. is just a naming convention - ajax will load on any address that can be looked up via dns, or it will work on an ip address as long as there is a server to respond to the request.
BUT - your page location and the ajax request need to be in the same domain for security reasons. To get round this restriction, you need to use something called JSONP
I have one server located at example.com running apache, serving my static html files.
I also have a json service located at api.example.com running python with cherrypy.
The user requests example.com and get the index html page. On that page I make an ajax request with jquery to the json service. document.domain returns example.com
$.ajax({
type: 'GET',
url: 'http://api.example.com/resource/',
dataType: 'json',
success: successCallback,
error: errorHandler
});
However, I can't see the response body for the ajax request in firebug. This leads me to believe that the browser (FF) doesn't support this.
What are the best methods to achieve this? I would prefer not to use any proxying on the apache backend for example.com if possible.
You can also use JSONP by adding callback=? to the end of the url. jQuery already knows how to handle these type of requests but it does require some server side changes to handle the callback param.
AJAX request is only supported on the same domain. However, you can write an http proxy in your preferred scripting language and make calls to that http proxy. You can check out this little tutorial on an AJAX proxy written in php.
try changing your domain in your sub-domain, like this
<script type="text/javascript">
document.domain = 'example.com';
</script>
if does not work, change your document.domain in your domain page too.
As far as I know, you can't do AJAX cross-domain.
Why is cross-domain Ajax a security concern?
Though I guess you could do an IFRAME workaround
Cross Sub Domain Javascript
Use document.domain to make the domain be the top level domain instead of the subdomain.
document.domain="example.com"
This is described in detail on MDN.