1

I am new to React-Native and PHP, I am trying to send an array from react-native to PHP on my server with code like this :

SaveData() {
let { RoomNo } = this.state
let q = [{"0":"BVR001","Stock_Code":"BVR001","1":0,"Qty":0},
         {"0":"BVR015","Stock_Code":"BVR015","1":0,"Qty":0},
         {"0":"BVR017","Stock_Code":"BVR017","1":0,"Qty":0}]

let url = 'http://192.168.100.99/SaveMNB.php'

fetch(url, {
  method : 'POST',
  headers : {
    'Accept' : 'application/json',
    'Content-Type' : 'application/json'
  },
  body : JSON.stringify({
    RoomNo : RoomNo,
    Orderan : q
  })
})
  .then(res => res.json())
  .catch(err => Alert.alert('ERROR',err.toString(),
                [{text: 'OK'}],{ cancelable: false }))
}

while on the PHP side my code is as below :

<?php
include("dbconfig.php");

$json = file_get_contents("php://input");

$obj = json_decode($json,true);

$RoomNo = $obj['RoomNo'];
$OrderanX[] = $obj['Orderan'];

$con = sqlsrv_connect($myServer,$MyDbR);
if ( $con === false ) {
    die( print_r( sqlsrv_errors(), true));
}

foreach($OrderanX As $Order) {
    //HERE WILL BE LOOPING THE ARRAY AND PUT IT INTO DATABASE
}

echo json_encode('SUCCESS');

?>

This will always return error because i am unable to pass the array from react-native to php.

The Error is

SyntaxError: JSON Parse error: Unrecognized token '<'

How to pass the array from react-native to php, thanks, helps are greatly appreciate.

EDIT :

However if i delete the foreach loop and change code to

echo json_encode($OrderanX);

it will return

[object Object],[object Object].[object Object]
Foolish Rhino
  • 11
  • 1
  • 3

1 Answers1

0

First, your react native code performs well though :)

So now our problem is in parsing the JSON payload, you have two options:

First method, using RecursiveArrayIterator:

<?php
$json = file_get_contents("php://input");
$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($jsonIterator as $key => $val) {
    if(is_array($val)) {
        echo "$key:\n";
    } else {
        echo "$key => $val\n";
    }
}
?>

Above code snippet's output (using Postman):

RoomNo => 1
Orderan:
0:
0 => BVR001
1 => 0
Stock_Code => BVR001
Qty => 0
1:
0 => BVR015
1 => 0
Stock_Code => BVR015
Qty => 0
2:
0 => BVR017
1 => 0
Stock_Code => BVR017
Qty => 0

After parsing it you can save to database (I think this way would be more tedious than next method).


Second method:

Parsing the JSON as you have done but with slight changes (Changed object attributes' access method):

<?php
$json = file_get_contents("php://input");

$obj = json_decode($json);

$RoomNo = $obj->RoomNo;

//Removed the [] as there is no need to define an object like this!
//It is already an array
//To define new empty array use: $varName = array()
$OrderanX = $obj->Orderan;

$response = array();
foreach($OrderanX As $Order) {
    //HERE WILL BE LOOPING THE ARRAY AND PUT IT INTO DATABASE
    // Save these variables to your database
    $zero = $Order->{'0'};
    $one = $Order->{'1'};
    $stockCode = $Order->Stock_Code;
    $stockQty = $Order->Qty;
    $stockItem=array(
        "0" => $zero,
        "1" => $one,
        "stock_code" => $stockCode,
        "qty" => $stockQty
    );
    array_push($response, $stockItem);
}

echo json_encode($response);
?>

Output of second method:

[
    {
        "0": "BVR001",
        "1": 0,
        "stock_code": "BVR001",
        "qty": 0
    },
    {
        "0": "BVR015",
        "1": 0,
        "stock_code": "BVR015",
        "qty": 0
    },
    {
        "0": "BVR017",
        "1": 0,
        "stock_code": "BVR017",
        "qty": 0
    }
]

Finally, hope this answer helps you :)

FYI, References used:

First Method:

Second Method:

  1. How to access object properties with names like integers?

  2. PHP's documentation