简体   繁体   中英

Unable to Post json data to a remote server using phonegap and ajax call

I am trying to send a json data from a javascript function running on a mobile data(phonegap framework) to a remote server. The code looks like below

 function sendJSONtoServer() { //alert("the call start was success to sendJSONtoServer"); $.ajax({ url: 'http://myserver.edu/~sas0090/save-userinfo.php', data: {'message' : "Hey Hi"}, type: 'GET', dataType:'json', crossDomain: true, contentType: "application/json; charset=utf-8", success: function(data) { //it works, do something with the data alert('Your comment was successfully added'); }, error: function() { //something went wrong, handle the error and display a message alert('There was an error adding your comment'); } }); alert("the call end was success to sendJSONtoServer"); }

I have researched that the same origin policy is not an issue here and most of the folks are able to get through this

http://samcroft.co.uk/2012/posting-data-from-a-phonegap-app-to-a-server-using-jquery/ http://www.indiageeks.in/phonegap-jquery-ajax-example-jsonjavascript-object-notation-response/

Note: I am connected to the remote server though vpn network. Could this be an issue. Also I am unable to get the failure message which are a part of the error: function() in AJAX

Any help will be highy appreciated.

Check <meta> tag with http-equiv="Content-Security-Policy" parameter in index.html file. Make appropriate(whitelist your domain) changes.

This may help "No Content-Security-Policy meta tag found." error in my phonegap application

If its php add this to the begining of the server side script to avoid the same origin policy message.

     if (isset($_SERVER['HTTP_ORIGIN'])) {
     header("Access-Control-Allow-Origin: *");
     header('Access-Control-Allow-Credentials: true');    
     header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
     }   

     if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
     if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
     header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
     if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
     header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
     exit(0);
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM