Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX cross domain

Here are two pages, test.php and testserver.php.

test.php

<script src="scripts/jq.js" type="text/javascript"></script> <script>     $(function() {         $.ajax({url:"testserver.php",             success:function() {                 alert("Success");             },             error:function() {                 alert("Error");             },             dataType:"json",             type:"get"         }     )}) </script> 

testserver.php

<?php $arr = array("element1",              "element2",              array("element31","element32")); $arr['name'] = "response"; echo json_encode($arr); ?> 

Now my problem: when both of these files are on the same server (either localhost or web server), it works and alert("Success") is called; If it is on different servers, meaning testserver.php on web server and test.php on localhost, its not working, and alert("Error") is executing. Even if the URL inside ajax is changed to http://domain.com/path/to/file/testserver.php

like image 572
Firose Hussain Avatar asked Aug 17 '10 19:08

Firose Hussain


People also ask

Can you do cross-domain AJAX?

Browser does not allow cross domain AJAX requests due to security issues. Cross-domain requests are allowed only if the server specifies same origin security policy.

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.

How do you bypass CORS in AJAX?

Rather, you would have to make the external request from your own local php script. Then you would call your local php script from Ajax, and this will work since you are accessing a local file, and thus not violating CORS.

How can make AJAX call in jQuery?

The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request. Parameters: The list of possible values are given below: type: It is used to specify the type of request. url: It is used to specify the URL to send the request to.


2 Answers

Use JSONP.

jQuery:

$.ajax({      url:"testserver.php",      dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)      success:function(json){          // do stuff with json (in this case an array)          alert("Success");      },      error:function(){          alert("Error");      }       }); 

PHP:

<?php $arr = array("element1","element2",array("element31","element32")); $arr['name'] = "response"; echo $_GET['callback']."(".json_encode($arr).");"; ?> 

The echo might be wrong, it's been a while since I've used php. In any case you need to output callbackName('jsonString') notice the quotes. jQuery will pass it's own callback name, so you need to get that from the GET params.

And as Stefan Kendall posted, $.getJSON() is a shorthand method, but then you need to append 'callback=?' to the url as GET parameter (yes, value is ?, jQuery replaces this with its own generated callback method).

like image 164
BGerrissen Avatar answered Sep 22 '22 20:09

BGerrissen


JSONP is a good option, but there is an easier way. You can simply set the Access-Control-Allow-Origin header on your server. Setting it to * will accept cross-domain AJAX requests from any domain. (https://developer.mozilla.org/en/http_access_control)

The method to do this will vary from language to language, of course. Here it is in Rails:

class HelloController < ApplicationController   def say_hello     headers['Access-Control-Allow-Origin'] = "*"     render text: "hello!"   end end 

In this example, the say_hello action will accept AJAX requests from any domain and return a response of "hello!".

Here is an example of the headers it might return:

HTTP/1.1 200 OK  Access-Control-Allow-Origin: * Cache-Control: no-cache, no-store, max-age=0, must-revalidate Content-Type: text/html; charset=utf-8 X-Ua-Compatible: IE=Edge Etag: "c4ca4238a0b923820dcc509a6f75849b" X-Runtime: 0.913606 Content-Length: 6 Server: WEBrick/1.3.1 (Ruby/1.9.2/2011-07-09) Date: Thu, 01 Mar 2012 20:44:28 GMT Connection: Keep-Alive 

Easy as it is, it does have some browser limitations. See http://caniuse.com/#feat=cors.

like image 39
jrh Avatar answered Sep 25 '22 20:09

jrh