Sharon Haim Pour
Sharon Haim Pour

Reputation: 6713

Problem with ajax calling from facebook app

I'm using the following code in order to make an ajax call to my server.
The code makes the call to the server and in return, it gets a list of all the friends that use the same app.

FB.getLoginStatus(function(response) {
  if (response.session) {
        uid = response.session.uid;
        access_token = response.session.access_token;
        $.getJSON(serverLink+"ajax.php?action=getFriendsApp", {token:access_token}
         ,function(data){
         var temp = data;
         if(true){
                var container = $('#friends_part_main');
                var fp = $('#friends_part');
                fp.show();
                var friends = data;
                for(var i in friends){
                    container.append('<a target="_blank" href="http://www.facebook.com/profile.php?id='+friends[i]+'">\n\
                    <img src="https://graph.facebook.com/'+friends[i]+'/picture" alt="friend" />\n\
                    </a>');     
                        }
                    }
                });
            }

If I run this code directly from the browser (www.mydomain.com/app) it works.
But when I run it from the canvas page (app.facebook.com) I get the foloowing error:

XMLHttpRequest cannot load http://www.mydomain.com/src/ajax.php?action=getFriendsApp&token=AAAC0kxh1WAcBAHo3s0QaVy34mgdnCNGvrDZCvIQsZCBHZC8ovR9IuYEFlUKRqK0GgJosWAD6Embg8QrN07vivE6mOuAZAtxUD7WpySDL3wZDZD. Origin https://www.mydomain.com is not allowed by Access-Control-Allow-Origin.

Can you figure out why??

Upvotes: 0

Views: 3195

Answers (3)

Dam Fa
Dam Fa

Reputation: 448

For me, the domain in the URL of my ajax page "ajax.php" and the URL of the ajax-calling-page "index.php" weren't exactly the same. "www" missed... You have to check that your two scripts domains (the calling script and the responding script) are exacty the same ! Check the "http" vs "https", check the "https://my-domain.com" vs "https://www.my-domain.com" etc. Hope it helps. xxx

Upvotes: 3

Anton Melnikov
Anton Melnikov

Reputation: 650

Your XMLHttpRequest is not allowed by access control allow origin because facebook load your application via secure https, but you could access only http. You can't load from other sundomain, protocol or port. Try JSONP with callback function. You can load Javascript code from any place, if your response contain not only data, but callback function, you could access any data from any place of your server (site).

Upvotes: 1

genesis
genesis

Reputation: 50966

You need JSONP or to allow ajax requests on your domain. You can force it with

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

Upvotes: 2

Related Questions