3

So I know this is a common problem and have seen a lot of people talking about it but feel that my situation is unique and maybe not as involved as others.

I have a host website and trying to build an iPhone app with JQ and PhoneGap.

I want people to be able to pass their score to my home domain from the app but am getting the dreaded: "Origin null is not allowed by Access-Control-Allow-Origin." when I try and call this:

$.ajax({
        type: "POST",
        url: 'http://www.homesite.com/thephppage.php',
        data: {
            'guid': '12333-54',
            'score': 52,
            'initials': 'tod'
        },
        success: function (data) {
            try {

                }
                else {

                }
            }
            catch (err) {
                alert(err);
            }
        },
        error: function (xhr) {
            alert(xhr.responseText);
        }
    });

Since this is calling out to a domain I own, is there something simple I can do to rectify this issue?

Thanks. T

4 Answers 4

5

That fact that you own both domains doesn't change the fact that ajax requests cannot be cross domain.

Since this is calling out to a domain I own, is there something simple I can do to rectify this issue?

Yes

Have a look at setting up CORS, which should allow you to make these cross-domain requests. Also, according to the jQuery docs, jQuery should support CORS requests—mostly

xhrFields (added 1.5.1) Map A map of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed.

$.ajax({ url: a_cross_domain_url, xhrFields: { withCredentials: true } }); In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it.


At present, due to a bug in Firefox where .getAllResponseHeaders() returns the empty string although .getResponseHeader('Content-Type') returns a non-empty string, automatically decoding JSON CORS responses in Firefox with jQuery is not supported.

Sign up to request clarification or add additional context in comments.

7 Comments

Ok, so different sites never pass variables to each other? I did not think this was something uncommon. Is there something I need to add to my server to allow this? Or is it a browser restriction?
@toddv - the most common way to handle this is with a proxy. You make an ajax call to a proxy on the same domain, which makes a call to wherever you want, then the proxy forwards the response back.
Thanks for the help Adam, I really appreciate it... Im just confused. I do not understand the difference of having one page in my app call another one just so it can do the same thing as the initial page. (I KNOW...I AM TOTALLY missing something here)... Ill try and read more on this.
@toddv - I understand your frustration. The thing is, your browser isn't smart enough to understand that you happen to own both pages. All the browsers knows is that they're separate domains, and so won't allow ajax requests between them for security reasons. Unless of course you implement cors.
So it looks like if I can figure out where to put THIS on my php page that things MIGHT work: Header set Access-Control-Allow-Origin * but where does that crazy mug go?
|
3

you will have to change the crossDomain to true.

check the jquery ajax api and options http://jqapi.com/#p=jQuery.ajax

Comments

2

To avoid calling a different domain from the app you can make a page on your host website which forwards the score registration to your home domain. You can then call this page on the host website.

You can use PHP to forward the data using HttpRequest::send

For example (not including authentication of the user):

$url = 'http://mydomain.com/score.php';
$r = new HttpRequest($url, HttpRequest::METH_GET);
$r->addQueryData(array('initials' => $initials, 'score' => $score));

try {
    $json = $r->send()->getBody();
    // output the response to forward it to the app
    echo $json;
} catch (HttpException $ex) {
    // handle error
}

5 Comments

Well I am passing the users initials, their score and their appId to my domain... so somehow I have to pass this from the app to the domain, right?
From what I understand you have a site A which is accessed by the iPhone, and at some point you want to make an Ajax call to a different site, B, to register a high score. Instead of calling site B you can call site A and let site A call site B.
Not quite. I have App A... and a button that says 'GET RANK!' ... push this and I want to call my website B's php page, sending their score and initials to that page (kind of like mydomain.com/score.php?initials=tev&score=12345) ... on the php page, I insert their score and send JSON back telling them their rank among all players.
You can use PHP to forward the data using HttpRequest::send: php.net/manual/en/function.httprequest-send.php
I dont think this will work for me because my app is a just a group of files saved together that get run inside a mobile browser... so local php files wont be served up.
0

WORKING!!! OH GLORY!!! (sort of): Here's what I did...

Instead of use the .ajax, I went the JSONP route (sort of) and added a tag to my head dynamically like so:

var head = document.getElementsByTagName('head')[0];
  script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'http://thesite.co/thepage.php?var1=123&var2=432&var3='ttt';
  head.appendChild(script);

I didnt even have to give it a CALLBACK method because (since I own the target site and know its coming) on my PHP side, I wrap the return with a methodName like this:

$encoded = json_encode($json); echo "testMethod(" . $encoded . ")"; This worked marvelously EXCEPT IN MY DARN iPhone and iPad simulators!!! (gosh I need to buy the real devices...) So I STILL dont know if this works on the actual devices but it works now in Chrome AND Safari... lets hope I can figure out how to make it work on that phone!

THANKS to everyone for their help!

==========SECOND BETTER MOBILE SOLUTION====================== This works better than the JSONP - dynamic Script solution...

In your head under your Phonegap and JQ calls insert this tag.

<script type="text/javascript">
        $(document).bind("mobileinit", function () {
           $.mobile.allowCrossDomainPages = true;
        });
    </script>

Then in your Phonegap.plist file in your XCODE Resources folder, add the domain to External Domains... ie. phonegap.com. (Leave off http or www).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.