I have a function in Jquery, that try get html from an page:
$.ajax({
type:'GET',
url: 'http://www.google.com',
success: function( data ) {
alert( data );
}
});
why does not works?
in firebug I see the communication headers.
you are violating SOP. To avoid SOP uou would likely need a server side script (on your host) to load the external url and return the data to your client side script, or use a service that provides a JSONP results.
Well, for security reasons, Javascript don't allow a page to load a page from external domains. These security reasons are to prevent users from form hijacking, xss attacks etc. If you still want to load external pages, you can use iframes, else you will need an openId kind of thing in your backend.
Cross domain $.ajax is not permitted due to security violation. The only cross domain call that you can do in jQuery is JSONP request.
Please read my answer to this question: JavaScript: How do I create JSONP?
Related
I need to scrape/parse some info from an external XML file (xml hosted on other domain) and place that info on my site.
I tried this, and didn't succeed:
jQuery(document).ready(function()
{
jQuery.ajax({
type: 'GET',
url: 'http://42netmedia.com/smart/signal_onAir10.xml',
crossDomain: true,
dataType: 'jsonp',
success: parseXml
});
});
function parseXml(xml)
{
jQuery(xml).find('nowOnAirTitle').each(function()
{
jQuery(".my-site-element").append(jQuery(this).find('nowOnAirTitle').text());
});
}
I hope I managed to explain properly.
PS. I am using jQuery because my site is hosted on WordPress
The short answer is that you cannot do what you're trying to do from Javascript running in a browser.
The same origin policy will block AJAX requests for URLs on different domains. There are a couple of exceptions to this policy:
If the target server supports CORS, it can indicate that cross-origin requests are OK. The URL you are trying to reach is on a server that does not support CORS.
If the target server supports JSONP, your script can retrieve data from the target server by using a <script> tag in your page with a src attribute pointing to the target URL and including a callback parameter to tell the server to wrap the data in a javascript function that returns the data. The URL you are trying to reach is on a server that does not support JSONP.
Yes, jQuery does allow you to make a JSONP request across to the other domain, but the response is not Javascript but XML. Your browser is trying to execute the XML as if it was Javascript and fails with a syntax error.
Any solution to this will require server-side support on the server which hosts your code. You could set up a proxy URL on your web server, but you'd need to do that very carefully because you don't want your server to be used as an open proxy. You could also use a cron job to grab the URL using curl and save it to a static file on your server, but that's probably a bit rude.
I looked for an answer to my problem everywhere but I didn't found what I want to know.
Here is what I want to do:
I have an url of an image, pdf or html page from the same domain and from other domains too. Is it possible to "download" them with AJAX?
But I don't want to have them physically on my server or anywhere else, I just want to use them directly on my website without having to upload them again (to save time).
I'm also having some troubles doing "XMLHttpRequest.getAllResponseHeaders()" when the content comes from an other domain. I tried with multiples url. I received nothing: "". Is it normal?
Thank you for your help ! :)
Unfortunately it is impossible to make AJAX requests for resources on domains external to the website's host domain, edit: unless they implement a workaround, like CORS or JSONP. I recommend doing some reading on Cross Origin Resource Sharing for more details.
As for resources on the same domain, you'd be storing those on your server anyway - you'd have to, in fact, because by its very nature it would be a part of your site. If you describe what you're trying to implement specifically (perhaps post a jsfiddle with your code), we could find a solution to your specific use case. Hope this helps.
[...] image, pdf or html page [...]
The types of these requests are very different. What you mean with 'download' is a little ambigious. If you're requesting a file via AJAX, this loads the value into a variable. It doesn't save the file to your computer.
[...] I received nothing: "" Is it normal? [...]
Yes, if the remote server isn't the same as you're currently on (also the same port) and also doesn't support CORS (cross-domain requests), the result will be blank.
If it's not possible to alter the remote server's cross-domain policies [and you have the permission to use their services], you could write a PHP script on your server that acts as a proxy. But don't forget to secure it to prevent mis-use. Also keep in mind that such a script can raise your traffic dramatically, so this should only be "Plan B".
You certainly can fetch images and html pages with AJAX and display them on your webpages.
The issues you are having with the xmlHttpRequest.GetAllResponseHeaders is most likely caused by the same origin policy. The browser prohibits you from interacting with the loaded data from another domain.
The server you are fetching the data from has to explicitly indicate that it allows your domain to fetch and display his resources by setting the Access-Control-Allow-Origin response header to that of your domain.
A way arround this is by using a proxy and setting the header yourself.
The following boilerplate code ( basically taken from the jquery api page ) loads your gravatar image ( delivered in png format ) from the stackoverflow website into a callback parameter. As others have noted, the same origin policy applies to ajax requests ( The sample code therefore can onlybe successfully run from the stackoverflow site context, eg. by opening a js console on this page ).
$.ajax({
method: "GET"
, url: "https://www.gravatar.com/avatar/d85e0ad5243245aabe2d34a3c9a296a9?s=32&d=identicon&r=PG&f=1"
, cache: false
, beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Length of data:", data.length );
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});
So, this Perl script:
http://hacheck.tel.fer.hr/xml.pl
will return a XML result based on the POST form-data that it receives.
I have a web-page on one of my domains (none of which are hacheck.tel.fer.hr) and I would like to use that Perl script via Ajax.
Now, the Same origin policy disallows me to send Ajax requests from my domain like so:
$.post('http://hacheck.tel.fer.hr/xml.pl', {'textarea': '...'}, function(data) {
// process data
});
The above code throws this error:
XMLHttpRequest cannot load
http://hacheck.tel.fer.hr/xml.pl.
Origin http://ecmazing.com is not
allowed by
Access-Control-Allow-Origin.
I would like to know what my options are (I would like to be able to use that Perl script). I know that placing my web-page onto the hacheck.tel.fer.hr domain would obviously solve my issue (and that may in fact be doable, but I'll have to contact the admin for that).
But are there any alternatives?
I've heard about CORS. Could it be used to solve my issue? If I understand correctly, with CORS you have to specify on the server that another domain is permitted, and than web-pages from that other domain can receive responses from your server (or something like that) :)?
I've heard about CORS. Could it be used to solve my issue?
Yes, but only in browsers that support it. The controller of hacheck.tel.fer.hr would have to set it up.
But are there any alternatives?
Proxy the request through your own server
I have two web-sites and two files:
provider.com/provide.js
viewer.com/index.html
viewer.com/index.html renders information to the user, and gets this information from provider.com. The file viewer.com/index.html looks like this (jQuery is used):
<script type="text/javascript"
src="http://provider.com/provide.js"></script>
<script type="text/javascript">
provide(function() { alert('works!'); });
</script>
provider.com/provide.js looks like this (I omit unnecessary details):
function provide(callback)
{
$.ajax(
{
'url': 'http://provider.com/',
}
);
}
I'm getting this message in all browsers: Failed to load resource: cancelled.
I have a feeling that I break some security restrictions. Could anyone explain what restrictions, if any. Thanks.
Eventhough the provide.js file is loaded from the provider domtain, it's still loaded in the context of the HTML page, so it's in the viewer domain. When the code tries to make the AJAX call to get information from the provider domain, you run into the cross domain limitation.
You can't use AJAX to load information across domains. However you can use JSONP as data format, then the ajax method will not do an AJAX call, instead it will use a script tag to load the information, which is allowed.
You can't request Javascript to send requests cross domain, for security reasons.
You can however make the request to the server which can retrieve the files and print the results for you, that Javascript can then request.
A brief introduction to the same-origin policy, described in other answers, can be found here:
http://en.wikipedia.org/wiki/Same_origin_policy
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.