problem with jquery load - javascript

I set up a js fiddle - just a simple jquery load function that loads the content of a url into a div, but it doesn't work. If I access the URL directly, it works fine. Any ideas what might be going wrong?
http://jsfiddle.net/heaversm/jLaPr/

The problem is that the url is on another server and you can't access it. If you want to call it, you should use $.ajax() and set the crossDomain option to true
Taken from the documentation of load():
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.

Due to browser restrictions, most Ajax requests are subject to the "same origin policy". That means that in most cases, you can’t use jQuerys ajax methods to fetch data from external domains without using a Proxy, YQL, JSONP or equivalent technique to get around this.
You should consider using this:
https://github.com/jamespadolsey/jQuery-Plugins/blob/master/cross-domain-ajax/jquery.xdomainajax.js
Using this plugin should allow the ajax example in your question.
Another option is to use a server-side proxy and then request that page using ajax. If your server can run PHP, try googling for something like "php ajax proxy" and you’ll get plenty results.

It's definitely a browser restriction (http://api.jquery.com/load#notes-0):
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.

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.

I don't get how JSONP is ANY different from AJAX

I don't see how the callback function in JSONP is any different from the success callback function in AJAX.
Given #1, I don't see how it is fundamentally more secure.
So is the only difference an artificial same-domain constraint with AJAX?
Why can't AJAX just allow cross-domain requests; if this can cause a security hole, wouldn't the attack just XSS a JSONP request?
Confused,
Max
An ajax call is an actual HTTP request from your client directly to a server. Ajax calls can be synchronous (blocking until they complete) or asynchronous. Because of same-origin security protections, ajax calls can only be made to the same server that the web page came from unless the target server explicitly allows a cross origin request using CORS.
JSONP calls are an interesting hack with the <script> tag that allows cross-origin communication. In a JSONP call, the client creates a script tag and puts a URL on it with an callback=xxxx query parameter on it. That script request (via the script tag insertion) is sent by the browser to the foreign server. The browser just thinks it's requesting some javascript code. The server then creates some special javascript for the purposes of this call and in that javascript that will get executed by the browser when it's returned, the server puts a function call to the function named in the callback=xxxx query parameter. By either defining variables of by passing data to that function, the server can communicate data back to the client. For JSONP, both client and server must cooperate on how the JSONP call works and how the data is defined. A client cannot make a JSONP call to a server that doesn't explicitly support JSONP because the exact right type of JSONP response has to be built by the server or it won't work.
So, the two communication methods work completely differently. Only ajax calls can be synchronous. By the nature of the <script> tag insertion, JSONP calls are always asynchronous.
In an Ajax call, the response comes back in a ajax event handler.
In a JSONP call, the response comes when the returned Javascript calls a function of yours.
In some ways, JSONP is a security hole that bypasses the cross-origin security mechanism. But, you can only call servers that explicitly choose to support a JSONP-like mechanism so if a server doesn't want you to be able to call it cross-origin, it can prevent it by not supporting JSONP. You can't make regular ajax calls to these other servers.
The browser makers can't really close this loophole because if they did zillions of web pages would break that either already use JSONP or load scripts from other domains. For example, every page on the web that uses jQuery off the Google or Microsoft CDNs would break because the browser wouldn't be allowed to download javascript from cross-origin domains.
JSONP was largely invented as a work-around to be able to make cross-origin requests. But, since JSONP requires explicit server support in order to work, it wasn't really a security problem because a JSONP call can only be made to a server that explicitly decided to allow that type of cross origin call. JSONP is used much less now than it used to be because CORS was invented as a more elegant way to control/allow this. CORS stands for Cross Origin Resource Sharing and it provides a means for a target server to tell a web browser exactly what type of cross origin requests are allowed and even to tell it which web page domains are allowed to make such requests. It is has much finer control available than JSONP and all modern browsers now support CORS.
Here's an example of how a cross-origin call causes problems. If you could load any arbitrary web page from any other web page or make any arbitrary ajax call, then imagine you were already logged into your webmail interface on Yahoo in so some other browser window. This means that your cookies are set to allow requests from your browser to fetch data from Yahoo. If the javascript in some other web page was allowed to make a webmail request to Yahoo (that would automatically have your cookies attached), it could then fetch all your webmail data and send it back to it's own site. One web site could rip off all the logged-in data from any other web site. All web security would be broken.
But, the way we have it today, as long as Yahoo doesn't support a JSONP interface that uses those same web cookies, it is safe from unauthorized JSONP requests.
Here are some other good writeups on the dangers of cross-origin ajax and why it has to be prevented:
Why the cross-domain Ajax is a security concern?
Why Cross-Domain AJAX call is not allowed?
Why are cross-domain AJAX requests labelled as a "security risk"?
JSONP's callback is not an actual callback. Rather, JSONP works by script injection. E.g., if you want to make a JSONP call, you insert this script element into the DOM:
<script src="http://example.com/ajaxendpoint?jsonp=parseResponse"></script>
The server's response will be something like this:
parseResponse({"json":"value"});
It will be evaluated in the window's global scope. So essentially JSONP is like a remote exec(), where the server is advised what string to create to execute.
This is very different from Ajax: with JSONP, the response is evaluated in the script's global scope; with XMLHttpRequest, the response is received as a string and not evaluated.
(Also, JSONP can only be used with GET, whereas AJAX allows any http method.)
Thus to your second issue, "I don't see how it is fundamentally more secure." Well, you are right, JSONP is actually extremely insecure. The server can return any script it wants, and do anything it wants to your browser!
Cross-domain requests are insecure because they can be used to reveal information about the current page to a page on another domain.
And you are right that any XSS attack can just use JSONP. The purpose of CORS is not to prevent XSS (if you have untrusted scripts running on your page you are hosed anyway).
The fundamental difference is that, for some reason, it's perfectly fine to load javascript files located on other domains (via script tag), but it is not OK by default to load other cross domain resources.
I'm with you, in that the delineation seems rather arbitrary. In jQuery, when you do a JSONP call, effectively you are creating a script tag, loading the resource, and then the jQuery library executes your script by calling the function defined in that JSONP result.
In my eyes, I cannot think of an additional vector of attack introduced by allowing cross domain AJAX which is not already gaping wide by allowing cross domain script loading, which is a common practice used everywhere (jQuery by googleCDN, advertising scripts, google analytics, and countless others).
From wikipedia
In addition, many legacy cross-domain operations predating JavaScript are not subjected to same-origin checks; one such example is the ability to include scripts across domains, or submit POST forms.

Soap Ajax cross domain problem

I'm trying to access a SOAP web service on another server using ajax but I'm getting an Access Control Allow Origin error. The web service returns XML so JSONP can't be used and the web service is also being used in another app so modifications is probably the last option. Any solutions?
If you can't do JSONP, then your options are:
Craete a server proxy at the domain of the page that can fetch the desired result from the other domain and relay it to you from the allowed domain.
If you're willing to limit your browser support to some modern browsers, then you can investigate Cross Origin Resource Sharing (CORS) which is a "safer" way to do cross-domain requests. You can read about it here.
Cross-domain ajax support via Flash which requires the placement of an appropriate cross-domain policy file on the host of the server you want to access. See here and here for some more info.
You can set up a server proxy at the domain of the page.
This page would then call the soap web-service and give you back the response.
This page can then be called via ajax from ui.
Found the probably most easiest way by using Ajaxpro 2, of course it's meant for .NET. http://www.ajaxpro.info/
otherwise, jfriend00's suggestions are the next best options.

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.

How to specify an external website for XMLHTTPRequest

When using an XMLHTTPRequest in javascript, I want to send it to an external website, rather than the one where the .js file is hosted. To send it to test.php on the current server, I would use
request.open("POST", "test.php", true);
but for the second arguemnt, how do I send it to another website. "example.com/test.php" looks for a file on the current server, and "http://example.com/test.php" justseems to outright fail.
You can't for security reasons. See the same origin policy for JavaScript.
There are some workarounds that exploit browser bugs or corner cases, but using them is not recommended.
The best approach is having a server-side proxy that receives Ajax requests, and in turn, sends HTTP requests to other servers. This should be carefully implemented by sanitizing input and whitelisting the types of requests that are sent, and the servers that are contacted.
This sounds like a bad case of Same Origin Policy, my friend :)
You can't (for the most part) use XmlHttpRequest to get data from an external website. What you can do, however, is dynamically create a SCRIPT tag and reference an external address. jQuery wraps this functionally as part of its ajax handling.
Indeed you can. Not in any browser although.
In Internet Explorer 8.0 there is XDomainRequest, an object enabling cross-domain requests. You would need to properly handle request made with this object on server by sending Access-Control-Allow-Origin header first with "*" or requester domain name.
Since you are doing some hacky things anyway, why not trying to use it on IE8 first?
If you have control over the server, you can use this header in the HTTP reply, although it may not work with all browsers.
Access-Control-Allow-Origin: *

Categories

Resources