Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phonegap + jQuery Ajax Post not working

I am trying to send data to a local page as POST data, from a phonegap app that I am working on using jQuery:

 $.ajax({
          method: "POST",
          url: "http://.../api_return.php",
          data: { name: "John", location: "Boston" }
        })
          .done(function( msg ) {
            alert( "Data Saved: " + msg );
          });

on my api_return.php page I have the following code:

<?php
print_r($_REQUEST);
?>

The strange thing is that if I make the url: "http://.../api_return.php?test=true", then my php returns the test=true, I cannot get it to return POST data.

I have tried:
<access origin="*" /> in config.xml
<uses-permission android:name="android.permission.INTERNET" /> in AndroidManifest.xml

like image 212
DanceSC Avatar asked Sep 16 '15 20:09

DanceSC


2 Answers

I managed to get it to work, but unfortunately I do not know which change ended up making this work. Here is a list of the changes I made:

1) add <access origin="*" /> in config.xml

2) add <uses-permission android:name="android.permission.INTERNET" /> in AndroidManifest.xml

3) add connect-src *; inside of content="" for the meta tag: <meta http-equiv="Content-Security-Policy" content="" />

4) Wrapped data in JSON.stringify. Ending ajax call:

$.ajax({
    type: "POST",
    url: "http://www.example.com/apicallback.php", // Example 
    data: JSON.stringify({ "name": "John", "location": "Boston" }),
    success: function(response) {
        console.log(response);
        alert(JSON.stringify(response));
    },
    error: function(e) {
        alert('Error: ' + e.message);
    }
});

5) Redirected to a second URL (one that was not using RewriteCond in the .htaccess folder)

like image 65
DanceSC Avatar answered Nov 17 '22 18:11

DanceSC


You may also check on "Content-type":"application/x-www-form-urlencoded" in your request header.

It may happen that you can find your post input in raw php://input but couldn't find in $_POST if you send without "Content-type":"application/x-www-form-urlencoded".

like image 37
Ks Sham Avatar answered Nov 17 '22 17:11

Ks Sham