Reputation: 91
I need to send POST data in the following format.
{
"buys": [
{
"productId": "1ae9ac1a37934fde92d7545cd6c93c13",
"amount": 200.00
}
]
}
Currently, my PHP script that the form submits to is.
<?php
$productId = $_POST['productId'];
$amount = $_POST['amount'];
$type = $_POST['name'];
//API Url
$url = 'https://********.com/post_test.php';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'type' => $type,
'productId' => $productId,
'amount' => $amount
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
?>
This is the output after submitting to form on the frontend, which isn't correct. I thought it would redirect to the inputted URL but I assume it's not meant to and it only posts? (as I typed that I to wondered if the output I'm seeing is from the webpage that I am linking at the top of the script, as that page simply echos the JSON as a string).
{"type":"buys","productId":"2ed913357e8842e9a38f0a16eb9703a9","amount":"45866"}
I really don't have any idea what to do next, or what to google to find a tutorial.
Some more details, I have a form that submits to the PHP script above. The variable $name is the "buys" in the requested format, the other variables are self-explanatory.
I'm sure there is just a way I need to format the JSON using my variables but I have no idea where to begin.
Upvotes: 0
Views: 228
Reputation: 796
You can try this
$jsonData['buys'][] = array(
'productId' => $productId,
'amount' => $amount
);
Upvotes: 1
Reputation: 111
Change your $jsonData
:
$jsonData = array(
'type' => $type,
'productId' => $productId,
'amount' => $amount
);
As follows:
$jsonData = array();
$jsonData[ $type ] = array();
$jsonData[ $type ][] = array(
'productId' => $productId,
'amount' => $amount
);
Upvotes: 1
Reputation: 654
So you want buys to be an array :
//The JSON data.
$jsonData = array(
$type =>
array(
'productId' => $productId,
'amount' => $amount
)
);
The output will be {"bugs":{"productId":"productId","amount":"amount"}}
Upvotes: 1
Reputation: 420
your json data should be like this
$jsonData = array(
$type => array(
'productId' => $productId,
'amount' => $amount
)
);
output :
{"busy":{"productId":"1ae9ac1a37934fde92d7545cd6c93c13","amount":"200.00"}}
Upvotes: 1