By Firose Hussain


2010-08-17 19:31:01 8 Comments

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

14 comments

@Ali_Hr 2018-03-03 12:25:43

I know 3 way to resolve your problem:

  1. First if you have access to both domains you can allow access for all other domain using :

    header("Access-Control-Allow-Origin: *");

    or just a domain by adding code bellow to .htaccess file:

    <FilesMatch "\.(ttf|otf|eot|woff)$"> <IfModule mod_headers.c> SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com|otherdomain.net|dev02.otherdomain.net)$" AccessControlAllowOrigin=$0 Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin </IfModule> </FilesMatch>

  2. you can have ajax request to a php file in your server and handle request to another domain using this php file.

  3. you can use jsonp , because it doesn't need permission. for this you can read our friend @BGerrissen answer.

@BGerrissen 2010-08-17 19:43:33

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).

@Eric 2011-10-23 12:41:03

Why do you need to return callbackName('/* json */') instead of callbackName(/* json */)?

@BGerrissen 2011-10-24 10:27:39

@eric the callback expects a JSON string. Theoretically, an object might work as well, but not sure how jQuery responds to this, it might throw an error or fail silently.

@Sanket Sahu 2013-07-11 09:54:29

And don't forget to add http:// or https:// in the beginning of the request.

@user2003356 2014-01-23 08:59:48

I'm getting the following error. SyntaxError: missing ; before statement {"ResultCode":2}. Where {"ResultCode":2} is response. Please advice.

@BGerrissen 2014-02-21 13:49:47

@user2003356 looks like you are returning plain JSON instead of JSONP. You need to return something like: callbackFunction({"ResultCode":2}). jQuery adds the GET parameter 'callback' to the request, that's the name of the callback function jquery uses and should be added to the response.

@user1566694 2014-03-19 18:49:30

The comma at the end of error: function(){...}, appears to cause an error. I'd take it out but edits must be 6 characters. so. that's good.

@srj 2014-05-13 17:36:56

The explanation given by @BGerrissen worked well for me after adding crossDomain: true, from the docs, " crossDomain (default: false for same-domain requests, true for cross-domain requests) Type: Boolean If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5) "

@Joël 2014-05-14 18:57:38

There is jsonp.jit.su it's a free JSON Proxy "Enables cross-domain requests to any JSON API." And it's on Github github.com/afeld/jsonp

@Vicky Chijwani 2016-07-20 09:16:56

It's 2016. CORS is now a widely supported standard, as opposed to JSONP which can only be described as a hack. @joshuarh's answer below should be the preferred one now.

@Sudip Bhandari 2016-07-26 08:23:02

why is it necessary to get the callback method in server?

@Josh Schultz 2017-07-24 15:02:53

For Microsoft Azure, it's slightly different.

Azure has a special CORS setting that needs to be set. It's essentially the same thing behind the scenes, but simply setting the header joshuarh mentions will not work. The Azure documentation for enabling cross domain can be found here:

https://docs.microsoft.com/en-us/azure/app-service-api/app-service-api-cors-consume-javascript

I fiddled around with this for a few hours before realizing my hosting platform had this special setting.

@Adorjan Princz 2014-11-29 10:43:53

You can control this via HTTP header by adding Access-Control-Allow-Origin. Setting it to * will accept cross-domain AJAX requests from any domain.

Using PHP it's really simple, just add the following line into the script that you want to have access outside from your domain:

header("Access-Control-Allow-Origin: *");

Don't forget to enable mod_headers module in httpd.conf.

@Jinu Joseph Daniel 2015-08-20 21:14:45

For cross origin AJAX requests, use the following jQuery plugin. https://github.com/jinujd/jQuery-Async-Form It works asynchronously, without reloading. It is not AJAX, but it does the task in most cases

@Eugene 2015-12-19 04:07:50

Tried to request translate.google.ru . Got following error(firefox): Load denied by X-Frame-Options: translate.google.ru does not permit framing. Error: Permission denied to access property "document"

@Jinu Joseph Daniel 2016-01-02 15:20:55

Yes..Its a hack..Contributions invited..onLoadFinished wont work in most cases

@Sarfraz 2010-08-17 19:34:00

You need to have a look at Same Origin Policy:

In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.

For you to be able to get data, it has to be:

Same protocol and host

You need to implement JSONP to workaround it.

@Aviator 2015-11-18 13:19:22

Can I get a working example using jsonp?

@Jason 2013-08-29 11:09:47

It is true that the same-origin policy prevents JavaScript from making requests across domains, but the CORS specification allows just the sort of API access you are looking for, and is supported by the current batch of major browsers.

See how to enable cross-origin resource sharing for client and server:

http://enable-cors.org/

"Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries. If you serve public content, please consider using CORS to open it up for universal JavaScript/browser access."

@BillyTom 2013-05-10 14:56:38

There are few examples for using JSONP which include error handling.

However, please note that the error-event is not triggered when using JSONP! See: http://api.jquery.com/jQuery.ajax/ or jQuery ajax request using jsonp error

@joshuarh 2012-03-01 20:51:37

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.

@TonyTakeshi 2012-07-23 04:40:20

Jsonp did not support post, put and delete. Your solution works great.

@SparK 2012-09-20 14:46:00

in PHP header("Access-Control-Allow-Origin: *");

@Warrior 2013-01-02 13:27:57

@SparK This code is fine when am using xmlhttpRequest.But not working when am using jquery.Post...

@Friederike 2013-04-26 12:29:57

@Warrior If you're using jQuery's .post() method you have to enable cross-domain support in jQuery. It is done with this: $.support.cors = true.

@Dan Esparza 2013-04-30 14:42:47

FYI - the official name for this is 'CORS' (Cross Origin Resource Sharing). More info: en.wikipedia.org/wiki/Cross-origin_resource_sharing

@Kristian 2013-07-29 18:33:54

easy peasy! thanks fellas

@Jasper 2014-01-22 18:04:50

It's just lazy to not whitelist particular domains and instead allow access from all domains...

@Jon Schneider 2014-01-24 03:12:52

What are the security implications of configuring a server in this manner?

@Sebastián Grignoli 2014-12-11 21:10:03

@JonSchneider the problem with this approach (just allowing any origin with *) is that any malicious page can capture the user's information on that server. Gmail had this problem once. It was inadvertently disclosing the user's contacts list.

@Sebastián Grignoli 2014-12-11 21:11:06

It would be better to allow only those domains that you want to share the data with instead of using the wilcard "*".

@Whome 2012-05-16 12:34:37

I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.

  • server script (.php, .jsp, ...) must return http response header Access-Control-Allow-Origin: *
  • before using jQuery ajax set this flag in javascript: jQuery.support.cors = true;
  • you may set flag once or everytime before using jQuery ajax function
  • now I can read .xml document in IE and Firefox. Other browsers I did not test.
  • response document can be plain/text, xml, json or anything else

Here is an example jQuery ajax call with some debug sysouts.

jQuery.support.cors = true;
$.ajax({
    url: "http://localhost/getxml.php",
    data: { "id":"doc1", "rows":"100" },
    type: "GET",
    timeout: 30000,
    dataType: "text", // "xml", "json"
    success: function(data) {
        // show text reply as-is (debug)
        alert(data);

        // show xml field values (debug)
        //alert( $(data).find("title").text() );

        // loop JSON array (debug)
        //var str="";
        //$.each(data.items, function(i,item) {
        //  str += item.title + "\n";
        //});
        //alert(str);
    },
    error: function(jqXHR, textStatus, ex) {
        alert(textStatus + "," + ex + "," + jqXHR.responseText);
    }
});

@jherax 2014-06-26 16:08:18

I wrote an answer for this question here: Loading cross domain html page with jQuery AJAXthe last one, supports https

@T30 2016-01-15 13:30:31

For the firest point: in PHP add this line to the script: header("Access-Control-Allow-Origin: *");

@zenio 2012-04-02 11:58:07

I use Apache server, so I've used mod_proxy module. Enable modules:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

Then add:

ProxyPass /your-proxy-url/ http://service-url:serviceport/

Finally, pass proxy-url to your script.

@Jacob Mattison 2010-08-17 19:34:52

Browser security prevents making an ajax call from a page hosted on one domain to a page hosted on a different domain; this is called the "same-origin policy".

@Bob Fincheimer 2010-08-17 19:53:44

@Paul Schreiber 2010-08-17 19:44:07

This is possible, but you need to use JSONP, not JSON. Stefan's link pointed you in the right direction. The jQuery AJAX page has more information on JSONP.

Remy Sharp has a detailed example using PHP.

@Firose Hussain 2010-08-18 12:14:07

Yes, Stefan sir's link, I am studying that.... Thanks a lot for you all...

@William Clemens 2010-08-17 19:43:33

From the Jquery docs (link):

  • 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.

So I would take it that you need to use jsonp for the request. But haven't tried this myself.

Related Questions

Sponsored Content

53 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

37 Answered Questions

[SOLVED] Is there an "exists" function for jQuery?

  • 2008-08-27 19:49:41
  • Jake McGraw
  • 652509 View
  • 2248 Score
  • 37 Answer
  • Tags:   javascript jquery

30 Answered Questions

[SOLVED] How to manage a redirect request after a jQuery Ajax call

56 Answered Questions

[SOLVED] How to check whether a checkbox is checked in jQuery?

17 Answered Questions

[SOLVED] Abort Ajax requests using jQuery

38 Answered Questions

[SOLVED] Setting "checked" for a checkbox with jQuery?

24 Answered Questions

[SOLVED] jQuery scroll to element

  • 2011-07-13 09:49:44
  • DiegoP.
  • 1877321 View
  • 1779 Score
  • 24 Answer
  • Tags:   javascript jquery

31 Answered Questions

[SOLVED] Add table row in jQuery

11 Answered Questions

[SOLVED] Serializing to JSON in jQuery

15 Answered Questions

[SOLVED] "Thinking in AngularJS" if I have a jQuery background?

Sponsored Content