Getting contents of a JSON array into PHP as part of a $_POST array

I am working on trying to increase my JavaScript skills beyond the beginner level, and decided to try to figure out how to add a feature to a recipe application that I built using PHP/mySQL. It involves dynamically adding input boxes for ingredients and textareas for directions to the Add Recipe form, the contents of which are to be processed along with the rest of the form submission. The number of ingredients and directions are pulled from two input boxes earlier in the form.

This is what I have managed to piece together in a separate JS file:

  1. I can read the number of ingredients and directions inputted and use that to dynamically add the correct number of form elements.
  2. I can get the input values and create a JS array of the ingredients, and a JS array of the directions.
  3. I can convert the arrays to JSON.

And this is where I am stuck. I now need to somehow get that JSON from my JS to my PHP controller to use with the PHP json_decode() function, so that I get two PHP arrays that I can process in my controller along with the rest of the form inputs in my $_POST array when I submit the form.

I am looking for a strategy or set of steps that will take me from the JS to the PHP, not the actual code at this time. I would like to try to figure that out for myself if possible. I tried Googling this situation, but all provided solutions have only served to confuse. Once I have an understandable set of steps, if I get stuck I will be back here with my code for more help.

This is a learning exercise - please don’t just hand me the code yet. Thank you.

There might be limitations depending on the size of the array. I can think of two approaches, one very much simpler as long as any size limits allow it.

Hint: What datatype are all $_POST values?

The $_POST values are either integers or strings. The JSON arrays have elements which are strings. I guess the longest would be the directions (some recipes might have upwards of 10 directions, each one containing multiple sentences). What kind of size limits are we talking about?

If I can get the JS JSON converted into a PHP array and into my controller method that processes the form, it does not need to be part of the $_POST array. I can process both in my controller to send off to the database. I would just like to send it to the controller at the same time as I send the $_POST array.

You missed the italicized. Try this:

<?php
declare(strict_types = 1);
error_reporting(E_ALL);
ini_set('display_errors', 'true');
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>POST datatypes</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
</head>
<body>
<h1>POST datatypes</h1>
<div>
<?php
if ($_SERVER['REQUEST_METHOD'] === "POST") {
  var_dump($_POST);
}
?>
</div>
<form action="#" method="post">
  <fieldset>
    <legend>Input Form</legend>
    <div>
      <label for="form_text_input">Text Input:</label>
      <input type="text" name="form_text_input" id="form_text_input">
    </div>
    <div>
      <label for="form_number_input">Integer Input:</label>
      <input type="number" name="form_number_input" id="form_number_input">
    </div>
    <input type="submit" value="Submit">
  </fieldset>
</form>
</body>
</html>

You don’t need JSON for this. You can send entire arrays to PHP in $_POST if you use in the input name, e.g.

<input type="text" name="child_name[]" />
<input type="text" name="child_name[]" />

When you submit that, $_POST['child_name'] will be an array of 2 elements.

1 Like

Thanks for your responses. I’m not sure what you are trying to show me with your code, @Mittineague. I already have my form set up and processed so that the contents are inserted into my database - except for the values from the form elements dynamically created by JavaScript.

@rpkamp, I know how to set up form inputs to get arrays. I do that quite often when I use the PHP framework that I built.

What I am trying to do is bridge the gap between JavaScript and PHP. In my JS file I have gotten as far as dynamically creating the form elements and gathering their input values into two arrays in my script.js. I now need to somehow get those arrays to my PHP controller as PHP arrays for insertion into my database along with the rest of the form contents.

That’s why I’m using JSON. But if there is another way, that’s fine too.

Again, I’m asking for the steps involved to bridge this gap, not the code. At this stage I’d like to try it for myself first, then ask questions if I get stuck. I either don’t understand the dynamics or I’m missing something obvious.

As an alternative to sending the arrays encoded as form values, as ScallioXTX suggests, you can also send the JSON as a POST request with the content-type application/json. When you send JSON to PHP in this way, it won’t be available via the $_POST superglobal. Instead you have to read from the request body and run the resulting string through json_decode().

1 Like

As @rpkamp says, those arrays are not necessary. You can send the entire form as a FormData object, and it will be available to the PHP script like a regular form submission. Here’s a link (with a spoiler alert):

Is that an official standard? From what I’ve read there was a W3C draft for this but it got cancelled.

https://www.w3.org/TR/html-json-forms/

Even if it’s not an official standard, its basic functionality has been adopted by every major browser, so they at least acknowledge its existance.

However, OP specifically states that he’s trying to transmit JSON he’s already created to PHP to use json_decode on them.

If he’s already got them in JSON, the JS JSON library has the command JSON.stringify().

At that point, all of the arrays are strings, ready to be decoded by PHP.
You can submit any number of strings as you want with a POST set.
If you actually wanted to, you could put your multiple JSON arrays into a singular JSON object, and stringify that and send it.

Oh that’s interesting, I wasn’t aware of that. Looks like that would have allowed the browser to directly submit forms as JSON?

Yes. AFAIK nobody implemented in though.

I’m going to give all your solutions a try today. Thanks. I’ll be back with an update later.

Simply that all POST values are strings with the hope that it would clue you in to thinking of stringifying the JSON.

I did not know about the possibility of sending JSON as JSON. That would simplify the stringify - json_decode steps.

I used stringify in my JavaScript already. I need to figure out how to get the JSON arrays from my javascript file, script.js (they are called jsonIngredients and jsonDirections) into my PHP controller file, Recipes.php, so that I can use json_decode() to convert them into PHP arrays. After that, I’m good to go. (Or try one of the other solutions mentioned here).

For a form submit I would probably do a

getElementById('hidden_input') 
hidden_input.value = my_stringified_JSON

Wait.

… are we talking about a file on the client or on the server?

I’ve dealt with all that. I need the bridge between those input values and my php code.

On the client. Nothing has gone to the server, and won’t until I get these arrays into my PHP controller and along with the $_POST array, process the form values so I can insert them into my database.

Okay, then the bit about it being in a file is moot, because you’ve read that into memory. You’ve stringified your values.
The question becomes “Do you want the processing to be visible.” IE: Do you WANT click a button, have the page reload pointing to myprocessorscript.php , or do you want to do it with AJAX in the background without leaving the page.