Home > database >  How to post json body to php api in flutter?
How to post json body to php api in flutter?

Time:12-29

I tried to post a JSON body to php api like this

var response = await http.post(
   Uri.parse("https://..."),
   body: {
     "orders": [
       {"id": 253, "userId": 13, "quantity": 2, "productId": 1},
       {"id": 257, "userId": 13, "quantity": 1, "productId": 3}
     ]
   });

and in the api I tried to access the variable like this

$data=$_POST["orders"];
echo $data[0]["id"];

but it always get the the error Undefined index can anyone help me please? I'm a flutter newbie.

CodePudding user response:

If you are passing a raw data to your request then you have to encode that to json before passing. Try code below :

var response = await http.post(
   Uri.parse("https://..."),
   body: jsonEnocde(
       {
         "orders": [
       {"id": 253, "userId": 13, "quantity": 2, "productId": 1},
       {"id": 257, "userId": 13, "quantity": 1, "productId": 3}
     ]
   }
));

CodePudding user response:

Can you try next on your server side:

<?php
$request = json_decode(file_get_contents('php://input'), true);

$data=$request["orders"];
echo $data[0]["id"];
  • Related