Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX cross domain call

I know about AJAX cross-domain policy. So I can't just call "http://www.google.com" over a ajax HTTP request and display the results somewhere on my site.

I tried it with dataType "jsonp", that actually would work, but I get a syntax error (obviously because the received data is not JSON formated)

Is there any other possiblity to receive/display data from a foreign domain? iFrames follow the same policy?

like image 553
jAndy Avatar asked Apr 01 '10 08:04

jAndy


People also ask

What is cross domain Ajax call?

CORS is a mechanism that defines a procedure in which the browser and the web server interact to determine whether to allow a web page to access a resource from different origin. Figure 2. Cross domain ajax request. When you do a cross-origin request, the browser sends Origin header with the current domain value.

How do you do a cross domain AJAX request?

For a successful cross-domain communication, we need to use dataType “jsonp” in jquery ajax call. JSONP or “JSON with padding” is a complement to the base JSON data format which provides a method to request data from a server in a different domain, something prohibited by typical web browsers.

Why is cross domain not allowed in Ajax?

Because of Same origin policy. The same-origin policy exists to prevent malicious use of resources. If there were no rules governing cross-domain script access, it would be trivial to wreak all manner of havoc on unsuspecting users.

Which are the two methods used for cross domain AJAX calls?

Two Approaches for cross-domain AJAX requests, Using JSONP (JSON with Padding) Enabling CORS (Cross-Origin Resource Sharing)


1 Answers

The only (easy) way to get cross-domain data using AJAX is to use a server side language as the proxy as Andy E noted. Here's a small sample how to implement that using jQuery:

The jQuery part:

$.ajax({     url: 'proxy.php',     type: 'POST',     data: {         address: 'http://www.google.com'     },     success: function(response) {         // response now contains full HTML of google.com     } }); 

And the PHP (proxy.php):

echo file_get_contents($_POST['address']); 

Simple as that. Just be aware of what you can or cannot do with the scraped data.

like image 91
Tatu Ulmanen Avatar answered Oct 12 '22 00:10

Tatu Ulmanen