B4J Question [BANano]PHP script unable to receive POST data

toby

Well-Known Member
Licensed User
Longtime User
I've been trying to let PHP script receive data POSTed by BANano unsuccessfully. Could someone kindly tell me what went wrong, please? TIA

The following php script snippet works for B4A.
Same script used for B4A to POST data to PHP:
    $post = file_get_contents('php://input');
    var_dump($post);   //output: empty
    $arr = json_decode($post, true); //output: $arr is null
    $order_id= intval($arr["order_id"]);

On BANano side, I use the code posted by @alwaysbusy here:


Complete php script file:
test1.php file used by BANano:
<?php
//1. connnect to mysql:

//////database/////////////////
$servername = "localhost";
$dbname = "xdurxttx_test";
$username ="xdurxttx_test";
$password ="xxxxxxxx";
/////////////////////////////

// Create connegtion
$conn = new mysqli($servername, $username, $password, $dbname);
//$conn->query("SET CHARACTER SET utf8");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//2. get post data
//read map data from POST method:
   /***/
    $post = file_get_contents('php://input');
    var_dump($post);
    $arr = json_decode($post, true);
    $order_id= intval($arr["order_id"]);
 
//3. retrieve data from mysql:
    try{
   
        $sql="SELECT * from orderitems
        WHERE order_id=$order_id ";
         echo $sql;  
        $result = $conn->query($sql);
        if ($result->num_rows > 0){
            $rows = array();
            while($r = $result->fetch_assoc())
            {
                $rows[] = $r;
            }
            print json_encode($rows);
        }
        else{
                echo '[{"result":0,"message":"no matching record"}]';
        }  
    }//catch exception
    catch(Exception $e) {
        echo '[{"result":"-100","message":"',$action, ", ", $e->getMessage, '"}]';
    }  


$conn->close();
?>
 
Solution
A couple of things:

1. please post B4J code, transpiled code is pretty useless.
2. besides the issue, but you are passing the wrong property 'orderid' while it should be 'order_id'
3. Remove those var_dumps in your php, they mess up everything as they are returned to the fetch and hence can not be processed because they are not valid json
4. You are returning an array, not a map in your json so you will have to change the PostString method accordingly (I changed it so it should be able to handle both now):

B4X:
Public Sub PostString(url As String, data As String)
mError = ""
    mString = ""
    
    Dim fetch As BANanoFetch
    Dim fetchOptions As BANanoFetchOptions
    Dim fetchResponse As BANanoFetchResponse
    
    Dim jsonObj As...

alwaysbusy

Expert
Licensed User
Longtime User
A couple of things:

1. please post B4J code, transpiled code is pretty useless.
2. besides the issue, but you are passing the wrong property 'orderid' while it should be 'order_id'
3. Remove those var_dumps in your php, they mess up everything as they are returned to the fetch and hence can not be processed because they are not valid json
4. You are returning an array, not a map in your json so you will have to change the PostString method accordingly (I changed it so it should be able to handle both now):

B4X:
Public Sub PostString(url As String, data As String)
mError = ""
    mString = ""
    
    Dim fetch As BANanoFetch
    Dim fetchOptions As BANanoFetchOptions
    Dim fetchResponse As BANanoFetchResponse
    
    Dim jsonObj As Object ' <-----------------------
    Dim Error As String
    
    fetchOptions.Initialize
    fetchOptions.Method = "POST"
    fetchOptions.Body = data
    fetchOptions.Headers = CreateMap("Content-type": "application/json; charset=UTF-8")
    
    fetch.Initialize(url, fetchOptions)
    Try
        ' wait for the response
        fetchResponse = BANano.Await(fetch)
        ' wait for the json part of the response
        jsonObj = BANano.Await(fetchResponse.Json) ' <----------------------- this will still crash if you use e.g. var_dumpor anything that returns invalid json
        
        ' overkill as we already have the json parsed here, but for demo's sake so we can do a GetString later
        Dim json As JSONGenerator
        If BANano.IsArray(jsonObj) Then ' <-----------------------
            json.Initialize2(jsonObj)  
        Else
            If BANano.IsMap(jsonObj) Then
                json.Initialize(jsonObj)
            End If
        End If
        
        mString = json.ToString        
        Success = True        
    Catch(Error)
        Log("Error: " & Error)    
        mError = Error        
    End Try    
End Sub

Alwaysbusy
 
Upvote 1
Solution

toby

Well-Known Member
Licensed User
Longtime User
Now I've finally realized that BANano expects a valid json string from PHP scripts, which is different from B4X's httpjob which accepts raw string.
B4X:
echo "test: var1=", $var1; //this line would cause BANano to fail due to invalid json string.
echo '[{"result":0,"message":"no matching record"}]';
 
Last edited:
Upvote 0

tango

Active Member
Licensed User
Longtime User
A couple of things:

1. please post B4J code, transpiled code is pretty useless.
2. besides the issue, but you are passing the wrong property 'orderid' while it should be 'order_id'
3. Remove those var_dumps in your php, they mess up everything as they are returned to the fetch and hence can not be processed because they are not valid json
4. You are returning an array, not a map in your json so you will have to change the PostString method accordingly (I changed it so it should be able to handle both now):

B4X:
Public Sub PostString(url As String, data As String)
mError = ""
    mString = ""
   
    Dim fetch As BANanoFetch
    Dim fetchOptions As BANanoFetchOptions
    Dim fetchResponse As BANanoFetchResponse
   
    Dim jsonObj As Object ' <-----------------------
    Dim Error As String
   
    fetchOptions.Initialize
    fetchOptions.Method = "POST"
    fetchOptions.Body = data
    fetchOptions.Headers = CreateMap("Content-type": "application/json; charset=UTF-8")
   
    fetch.Initialize(url, fetchOptions)
    Try
        ' wait for the response
        fetchResponse = BANano.Await(fetch)
        ' wait for the json part of the response
        jsonObj = BANano.Await(fetchResponse.Json) ' <----------------------- this will still crash if you use e.g. var_dumpor anything that returns invalid json
       
        ' overkill as we already have the json parsed here, but for demo's sake so we can do a GetString later
        Dim json As JSONGenerator
        If BANano.IsArray(jsonObj) Then ' <-----------------------
            json.Initialize2(jsonObj) 
        Else
            If BANano.IsMap(jsonObj) Then
                json.Initialize(jsonObj)
            End If
        End If
       
        mString = json.ToString       
        Success = True       
    Catch(Error)
        Log("Error: " & Error)   
        mError = Error       
    End Try   
End Sub

Alwaysbusy
please write a php script file for poststring
 
Upvote 0

tango

Active Member
Licensed User
Longtime User
Now I've finally realized that BANano expects a valid json string from PHP scripts, which is different from B4X's httpjob which accepts raw string.
B4X:
echo "test: var1=", $var1; //this line would cause BANano to fail due to invalid json string.
echo '[{"result":0,"message":"no matching record"}]';
did you solve this problem?
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
did you solve this problem?
1. It is a MISTAKE to post in old threads
2. The solution is to return a VALID JSON from php. See his post. He posted the solution already!
 
Upvote 0
Top