0

If I have a form in a view to submit a field "id" and the following code in "file.php" to receive it, how should I encode and send it?

"file.php"

$body = json_decode(file_get_contents("php://input"), true);
echo $body['id'];

"in the view"

<form action="file.php" method="post">
    <input type="number" name="id" />
    <input type="submit" />
</form>
David Rios
  • 377
  • 4
  • 9
  • You should probably use something like JavaScript to prevent the normal form submission, then use AJAX to send the data by serializing the form. etc., – ArtisticPhoenix Feb 27 '19 at 21:47
  • 1
    Why does JSON need to be involved? Why not just submit the form and get the id from `$_POST['id']`? – Don't Panic Feb 27 '19 at 21:49
  • i get the $_POST['id'] example but i am trying to understand how the encode/decode works. – David Rios Feb 27 '19 at 21:53
  • 1
    Ah, okay. That makes sense. These posts may be helpful: https://stackoverflow.com/questions/8599595/send-json-data-from-javascript-to-php, https://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery – Don't Panic Feb 27 '19 at 22:01
  • thanks for the help, this one helped me https://stackoverflow.com/questions/8599595/send-json-data-from-javascript-to-php – David Rios Feb 28 '19 at 13:22

1 Answers1

0

Based on you PHP code, the JSON string that are going to be received is like this

{"id": 123}

So, you can encode it like this:

$arr['id'] = 123;
$json = json_encode($arr);

or like this:

$arr = array("id" => 123);
$json = json_encode($arr);
Afif Zafri
  • 640
  • 1
  • 5
  • 11