8

In phonegap I have an issue while calling a PHP file using jQuery AJAX. The error that occurs while calling the file is:

No 'Access-Control-Allow-Origin' header is present on the requested resource

Google said to put this code header('Access-Control-Allow-Origin: *'); in the current PHP file header. I put the code in the header, but still no changes. I've attached my jsfidde with it.

The file connectionsqlphp.php code is here

<?php 

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
echo "hi";

?>
cryptic ツ
  • 14,653
  • 9
  • 49
  • 77
Sri
  • 633
  • 2
  • 7
  • 20
  • 1
    do you have `` in your config.xml file? – Dawson Loudon Feb 14 '14 at 07:39
  • @Dawson Loudon yes I have – Sri Feb 14 '14 at 07:45
  • are you testing on the phone/simulator or inside your browser? Origin errors are more likely to happen if you are testing on a desktop browser. – Ekim Feb 14 '14 at 08:45
  • I'm not a php expert, but are you sure `echo "hi"` will generate a valid json output??? – QuickFix Feb 14 '14 at 08:49
  • @Ekim I checked in browser in phone its not giving any error just simply blink thats all.. – Sri Feb 14 '14 at 10:10
  • @QuickFix I just want to display hi via json in my file I don't know how let me know if you have any ideas about this.. – Sri Feb 14 '14 at 10:12
  • Looks realy Like a CORS problem, there are some great resources and answers here: http://stackoverflow.com/questions/19821753/jquery-xml-error-no-access-control-allow-origin-header-is-present-on-the-req – Maurice Feb 14 '14 at 11:49

1 Answers1

10

There should be no cross origin issue in phonegap/cordova as long as you configure properly access origin in config.xml.

It's normal that you have this message when testing from a browser if you miss some CORS headers.Try adding :

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');

But once again you don't need those headers for a phonegap app.

When you do echo "hi";, your're not sending json but sending a text "hi". (just writing json in the header does not format what you echo).

I think you should either use $.get in the javascript and remove header('Content-Type: application/json'); from php so that the app expects a simple text or modify your php to really send JSON.

for ex:

echo "{message:\"hi\"}";
QuickFix
  • 11,323
  • 2
  • 34
  • 49