Why are AJAX requests limited to same domain? - javascript

Something I find really confusing, is why are AJAX requests limited to the same domain? What is the reasoning behind this?
I don't see any problem with requesting files from external locations, also servers making XMLHTTP requests seem to get and post to external locations fine.

Picture this :
You come on my fabulous website www.halfnakedgirls.com. You have fun watching what looks like technical documentation on human physiology, but behind your back, some lines of JavaScript are executing some request to another domain, let's say www.yourpaypallike.com.
Requests like http://www.yourpaypallike.com/account/transfer?to=badguy#evilwebsite.com&amount=984654 or http://www.mymailprovider.com/mails/export?format=csv.
Do you now see why it is forbidden ? =)

Tom, it is not "Ajax request limited". AJAX is based on JavaScript. For security reason JavaScript is prohibited access on cross domains. If you really want to do cross domain Ajax, you can do a hack.
YourPage(Ajax) ----> YourServer ----> ExternalDomain
You can call a page in your server using Ajax, Your domain will call to external domain using server side , and get the result then return to you as Ajax response.
Of course the request done to the ExternalDomain server will be called WITHOUT sending cookies for ExternalDomain that reside in your browser's memory. That's because the request is done by your server and not your browser.

It's for security purposes - if a website could execute AJAX calls to any domain they wanted on the client side, it poses a serious risk.
There are ways around this though - you could have your AJAX call a PHP script on the same domain, which in turn can call a script from another domain and return it. This wouldn't be using the browser as the communication medium though, it'd be using your web server.

Here is some information to satisfy your question:
http://en.wikipedia.org/wiki/Same_origin_policy

Related

Get any page with AJAX

I'm new to AJAX and I have what I think is a simple question. I know you can create a page that will respond to an AJAX call. Is it possible to just get any page with an AJAX call?
So I mean to say, can I do anything with an AJAX call that I could do with a URL?
EDIT #1
Thanks for all the responses! Really helped clarify!
Yes and no.
AJAX is a powerful mechanism by which you can retrieve and/or load data into the DOM in a flexible manner. You can do things like grab the content of another page and display all or portions of it on your page. There is a catch however.
Due to security reasons, you cannot depend on being able to make an AJAX call in a cross-domain manner unless the server on the other domain is properly configured. This is known as Cross-Origin Resource Sharing (CORS). You can read more about that here - http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Alternatively, some servers will expose API's that work with JSONP (JSON with Padding), which is a sort of workaround for the Same Origin Policy (SOP) that normally prevents cross-domain requests of this nature. In JSONP, the remote endpoint in essence wraps the response in a javascript function. You can read more about JSONP here - http://en.wikipedia.org/wiki/JSONP
You are limited to requests within the same domain, unlike a normal URL. There are ways around it using CORS or JSONP in that case.
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
No.
One example is that you can't use AJAX to upload or download files. One workaround for this is to target the upload or download to a hidden iframe and poll that frame for a response. Update: it seems some support for this is part of HTML 5 (see https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications).
A second example is navigating the user to another page. You can load a second page and replace the contents of the window with it, but the URL will still be the original page (the "refresh" and "back" features of the browser will behave accordingly).
A third is cross-domain requests. AJAX calls are limited to the domain the page originated from.

Is there a way to mimick a google/yahoo finance Ajax call?

I am aware if you try to scrape the google/yahoo finance websites you're at risk of being blocked by their server. I was therefore wondering what if you could spoof the google/yahoo ajax call (which they use to update the prices on the webpage if you leave it open) back to the server each time you wanted a price, surely the google/yahoo server wouldnt count this towards the daily request limit?
Is this possible?
If you try to do it via JavaScript, you'll probably run into problems with the same origin policy. You can't do ajax requests to Google/Yahoo from one of your own sites (when not using an official JavaScript API provided by Google/Yahoo).
You can try it using another programming language by inspecting the http calls using Wireshark, Fiddler or similar, and rebuilding the request with the correct headers. This will probably violate the terms of service though (getting you banned), and might even be illegal.

How to get an Ajax request from an external server using client side JavaScript

I'm trying to write a utility in my blog system as a post. The limitations are that I can not run any server side code. I can only run client side (JavaScript) code. I would like to send a request to an external domain and parse that result.
For example, based on how people use my utility, I would want to be able to get the HTML of a page such as http://example.com/getPage.html?page=A, which might contain:
<html>
...
<body>
...
<table id="targetTable">
<tr><td>Some Data</td></tr>
<tr><td>Some Data</td></tr>
<tr><td>Some Data</td></tr>
</table>
... which I would store in a JavaScript string and then query to find the data I want.
I want to query this page from an external domain (i.e. my script is not running on http://example.com, nor am I affiliated with http://example.com) using client side code only.
I'm using jQuery and it says that the jQuery.get() method would not work due to the same origin policy. Is there any way to do what I want some other way? For example, loading an iframe then reading its html property somehow?
You might want to take a look at JSONP and the more recent CORS. Using these technologies still doesn't guarantee that you'll be able to do what you want using only Javascript and no server side code...
I'm afraid that is impossible. You can work around it using a convention called jsonp, but that will only be able to retrieve json objects (even if those of course can contain html-strings). But a server can only respond to a jsonp request if it has builtin support for it.
The most straightforward workaround for your problem would be to create a tiny server that gets html pages and returns json-data. Then you can send your ajax calls to that server (like this: http://www.yourserver.com/?page_to_get=http%3A%2F%2Fwww.example.com%2FgetPage.html%3Fpage%3DA), let it fetch data from example.com and return it to your client side script as json.
Just to strengthen my argument, a piece quoted from jQuery's AJAX page:
Due to browser security restrictions,
most "Ajax" requests are subject to
the same origin policy; the request
can not successfully retrieve data
from a different domain, subdomain, or
protocol.
Script and JSONP requests
are not subject to the same origin
policy restrictions.
You can load an iframe from another domain or make POST calls to another domain.
Luckily for our security but unfortunately for your problem, you can't read anything with Javascript due to the Same Origin Policy.
If you can't get any cooperation from the other domain. eg: with JSONP enabled or a window.postMessage then the only solution you have is to use a web server as a proxy.
The server that delivers your page or a free(if your trafic isn't huge) instance like Google App Engine, where you have a hand on.
You call this server in ajax, JSONP or an iframe + window.postMessage with a generic service that will fetch the page content and deliver it to the browser.

Help! me with "AJAX"

I am working around AJAX for few months now and i see Ajax request as following,
Pass parameters to background page (PHP/ASP/HTML/TXT/XML ... what else can be here?)
Do some processing on server
Get back the results and show to client (HTML/XML/JSON ... what else can be here?)
If there is something else to add on Request lifecycle please I will be glad to know?
Now I have some questions around AJAX and i will try to frame them one by one.
How many concurrent AJAX request can be made?
Yes there is timeout period in AJAX but considering the web2.0 scenarios and possibilities with the Network what is the timeout period? Best practice?
Consider scenario that if user invoke AJAX Request and it’s in process on the server and meanwhile user left the page. Will the processing on the server will be left in haft way? Or all the execution on server will be done and response is sent back to browser? What will happen?
Is it a strict requirement that we should have a server page (PHP/JSP/ASP) to take the AJAX request? As with this approach considering wide use of AJAX now a day, on server we need page per request (or few pages to server more than one request) which is something become difficult to maintain.
Can we have something else instead of server side page (PHP/ASP etc.) like web service or something which can be directly requested from AJAX (JavaScript) like URL? If yes how? This can reduce need of additional server side pages.
AJAX request also supports the Authentication. In what scenario this is used? Is it mandatory?
Comet is something which I heard lot about. My understanding is that it’s just some pattern in which AJAX is used to get updated data by using polling mechanism. Is it right? Please provide your views/insight.
Security risk using AJAX? How can it can be mitigated (Encryption/Decryption or something else)?
Thanks all,
Depends on the browser. It follows the same rules as concurrent HTTP requests everywhere else in the browser.
Ditto.
Pretty much the same as the user hitting the Stop button on a regular page.
An HTTP request must request a URI. How you handle that on the backend is up to you. The term "page" doesn't really fit — that is an HTML document with associated resources (stylesheets, images, etc). Most systems don't have a 1:1 mapping between server side programs and resources. In an MVC pattern, for example, it isn't uncommon to have a shared model and a controller that just switches between views for determining if to return an HTML document or the same data expressed in JSON.
A web service is just a server side program that responds in a particular way, lots of people write them using PHP, JSP or ASP so the question doesn't really make sense.
No, it isn't mandatory. You use authentication when you need authentication. There is no special "ajax authentication", that is usually just using the same cookies that are used everywhere else in the site.
No, the point of Comet is to avoid polling. See http://en.wikipedia.org/wiki/Comet_%28programming%29
Requests containing data are sent to the server. Responses containing data are returned from the server. The security implications are no different to any other HTTP request you handle.
You must use the URI to use it

Cross Domain Limitations With Ajax - JSON

When requesting (ht|x)ml with ajax you can only send requests to the same domain. But if you request JSON you can send it to any domain. Why?
I'm told it's for security but why would a website do something malicious via ajax rather than just directly if that makes sense.
Check out this wikipedia article.
The reason why JSON is 'safe' is because you have to pass it through a callback. The remote site will run return JSON and your javascript library will not just run it blindly but try to pass it to a function you specify, like jsonpCallback( response ). Since you aren't running the remote code directly much more is under your control and all is mostly well in the world.
The reason it's called JSONP has actually little to do with JSON itself. Doing a cross-domain ajax request is as simple as adding the <script src="http://url.com/data.js></script> tag to your HTML web page; this is the base concept of JSONP and cross-domain ajax.
What happens is that the data.js file is interpreted by JavaScript. This gives us the ability to get data from that data.js file (which is located on another domain), if for example it loads a function that is available in the current scope.
Here is an example of why someone would hack an AJAX request.
https://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/
http://directwebremoting.org/blog/joe/2007/04/04/how_to_protect_a_json_or_javascript_service.html
Injecting JSON directly in your page is not secure at all.
You offer to the loaded scripts full access to the resources in your page(data, cookies, logic).
If the injected code is malicious, it can run actions on your server, post back data to their server(POST is allowed cross domain, not the response but your data are sent anyway), etc...
We're building a web app that makes a heavy use of cross domain accesses.
To solve this problem, we came with a rather simple JSONP sandboxing solution.

Categories

Resources