Is it possible to send a json array via post?

24,453

Solution 1

The problem your having is this string is NOT Proper JSON: [500,'hello world']

this would be proper JSON [500,"hello world"]. JSON is very strict on formatting and requires that all string values be wrapped in double quotes and NEVER single quotes.

the proper thing to do to avoid problems, would be to use the php functions json_encode() and json_decode()

for example,

<?php
    $myarray[] = 500;
    $myarray[] = "hello world";
    $myjson = json_encode($myarray);
?>
<form name="input" action="post.php">
    <input type="hidden" name="json" value="<?php echo $myjson ?>" />
    <input type="submit" value="Submit">
</form>

and in the post.php you would read it like so,

<?php
    $posted_data = array();
    if (!empty($_POST['json'])) {
        $posted_data = json_decode($_POST['json'], true);
    }
    print_r($posted_data);
?>

the true flag in json_decode() tells the function you want it as an associative array and not a PHP object, which is its default behavior.

the print_r() function will output the php structure of the converted JSON array:

Array(
    [0] => 500
    [1] => hello world
) 

Solution 2

Is the API a 3rd party on or made by you?

If it is yours, consume the data sent by your form should be as simple as this on your API:

<?php
    $data = json_decode($_REQUEST['json']);

    echo $data[0]; // Should output 500
    echo $data[1]; // Should output hello world

If it is a 3rd party, probably they expect you to send the json in post body. To accomplish that, follow this post: How to post JSON to PHP with curl.

Share:
24,453
user962449
Author by

user962449

Updated on November 07, 2020

Comments

  • user962449
    user962449 over 3 years

    Im trying to send a json array to a php post request.

    $myarray[] = 500;
    $myarray[] = "hello world";
    

    how can I send $myarray json data to a php post request?

    Here's what I tried:

    <form name="input" action="post.php">
    <input type="hidden" name="json" value="[500,'hello world']" />
    <input type="submit" value="Submit">
    </form>
    

    Im testing the API and was told it only takes json data...but I can't seem to get it to work. My guess is Im sending the json data wrong. Any thoughts?

  • mario
    mario over 11 years
    Good catch. However you also need to use single quotes then for the value='..' attribute, or better yet apply htmlspecialchars(), so the JSONs double quotes don't break the HTML syntax.
  • Sheac
    Sheac over 11 years
    oops, yeah was going a bit fast, good catch yourself. forgot about the quotes on the input tag lol. If you wanted to avoid the special characters and avoid the single quotes on the input, you could just base64_encode the json, then on the other end base64_decode it to avoid any complications. similar to how facebook does their posted json signed request on load of a facebook application.