Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cant I load an external resource from jQuery load method?

Tags:

jquery

ajax

In the process of learning Ajax requests using jQuery, I tried to load google home page on the click of a link. So I wrote something like:

$("#ajax").click (function (event) {
    $("#g").html("Loading...");
    $("#g").load("http://www.google.com");
    event.preventDefault ();
});

And somewhere in body:

<a id="ajax" href="http://www.google.com">Load file ajax way</a>
<div id="g">Click the above link to load the page...</div>

Which didn't work and initially I thought there is some syntax error or something. But later when I replaced the google url with a static html file on server, it worked correctly.

$("#g").load("Temp.htm");

Is it designed to work like this (if yes, why?) or am I doing something wrong?

EDIT: Please can anyone explain (or refer) the security problem introduced by cross domain ajax calls? In other words, why it is safe to open another browser tab and open google but NOT from within the page? Is it to protect caller or callee?

like image 346
Hemant Avatar asked Aug 18 '09 08:08

Hemant


3 Answers

Jquery uses an ajax (XMLHttpRequest) request to load the data, but the browser allows this for resources on the same domain. (The answers above mention the Same origin policy). That's why it works with Temp.htm, but not www.google.com.

  • One way to get around this is to create a server script that will load the page for you - basically a proxy. Then you call

    $('#g').load("load.php?url=google.com")
    
  • The other solution is to use iframes for communication - I found this library, that seems to be what you need: jquery-crossframe

  • A third options is JSONP but that would not work it your case.

My opinion - go for the first option with a server-side proxy.


Why is there a same origin policy?

Imagine that you are checking some stuff on your ebay account. Then in another tab you open my site, where I have a script that makes a series of requests to ebay (you are still logged in) and bids you for an Audi A8 without you even noticing. Annoying... If it was your bank it can directly steal money from you.

The irony is that despite the same origin policy, the above attack is still possible.

like image 113
Emil Ivanov Avatar answered Nov 18 '22 05:11

Emil Ivanov


You're not allowed to make cross-domain AJAX calls for security reasons - see Same Origin Policy.

like image 44
Greg Avatar answered Nov 18 '22 06:11

Greg


This is due to security. You can read all about it along with a solution over at yahoo.

like image 1
Andy Gaskell Avatar answered Nov 18 '22 07:11

Andy Gaskell