0

I made a 'voting' API for a topsite for the sites registered to use.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

    <script type="text/javascript">

        var id = 1;

        $(document).ready(function(){
            $.getJSON("http://mysite.com/index.php?page=vote", { id: id, hasVoted: 'unknown' }, function(data) {
                if(data == 2) {
                    window.location.replace("http://mysite.com/index.php?page=vote&id=" + id);
                }
            });
        });

    </script>

Basically, I give the user's their ID and then they put that code in their files. The site returns a number and upon that, it redirects the user or not to voting.

So, testing on localhost that code throws this error:

 XMLHttpRequest cannot load http://mysite.com/index.php?page=vote&id=1&hasVoted=unknown. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

If I use this code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

    <script type="text/javascript">

        var id = 1;

        $(document).ready(function(){
            $.getJSON("http://mysite.com/index.php?page=vote&callback=?", { id: id, hasVoted: 'unknown' }, function(data) {
                if(data == 2) {
                    window.location.replace("http://mysite.com/index.php?page=vote&id=" + id);
                }
            });
        });

    </script>

Then it does nothing. It throws no error. ( While data is supposed to be equal to 2 ( When checking that URL directly, it returns 2 ) ).

And, if I try to do a little test, and do alert(data); It throws nothing still.

I'm completely clueless about this. Anything will help.

1 Answers1

2

Well known problem, the origin control of the browser:

A browser doesn't allow you to make ajax requests to 'cross-origin' domains by default. Cross origin means, that either the port or host is different. Therefore you can't send requests to site http://siteB/ while the script to make the requests is hosted on site A.

Simple solution would be to host everything on one domain and make the url relative. If that's not possible, you have to find another way no make cross-origin calls. Some examples:

  1. JSONP (only GET)
  2. CORS (work's very good with modern browser)
  3. include an ifram + use PostMessage between the windows
  4. proxy script

EDIT: What I would do, is first allow your API-SERVER some stuff, by setting these headers:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Authorization");

Be aware, that this isn't working properly with the Internet Explorer, so you have to use: XDomainRequest. But this doesn't allow you sending headers. Please see my question a couple days ago, if you have to send headers cross-origin

Community
  • 1
  • 1
Johannes Staehlin
  • 3,680
  • 7
  • 36
  • 50