0

I'm trying to figure out the best way to submit a form with a complex structure that is dynamically generated in Javascript to a PHP script via the POST method.

The form has this kind of hierarchical structure:

<div class="item">
  <textarea class="subitem_textarea"></textarea>
  <input type="text"/>
  <input type="text"/>
</div>
<div class="item">
   <textarea></textarea>
  <input type="text"/>
  <input type="text"/>
  <input type="text"/>
</div>

The number of items is variable and can't be known in advance since items are created by the user. Each item has one <textarea> field, but a variable number of <input type="text"/> fields, since those are also created by the user.

I need to save the content of the form into a database, in a way that preserves this structure, so the PHP script must be able to know which field belong to which item.

I guess that one way to do this is, on the client side (Javascript + jQuery), to arrange for the fields to be given names in such a way that, on the server side (PHP), I can figure that out. For instance, using Javascript + jQuery, I could arrange for the HTML of the form that is dynamically generated on the client side to be:

<div class="item">
  <textarea name="textareas[0]"></textarea>
  <input type="text" name="texts[0][0]"/>
  <input type="text" name="texts[0][1]"/>
</div>
<div class="item">
  <textarea name="textareas[1]"></textarea>
  <input type="text" name="texts[1][0]"/>
  <input type="text" name="texts[1][1]"/>
  <input type="text" name="texts[1][2]"/>
</div>

Then, on the server side, I can just recover the structure in PHP by inspecting the $_POST array. However, I can't help but think that I shouldn't have to bother with naming fields in a particular way, that it should be possible to recover the content and structure of the form in a simpler way.

For instance, in order to make various Ajax calls, I already need to store the content and structure of that dynamically created form in a Javascript object as it's being filled, which I send to the server using JSON.stringify when I make the Ajax call and recover in PHP with json_decode

For instance, if I store the content and structure of the dynamically created form in a Javascript object as it's being filled (which I already have to do anyway in order to make various Ajax calls that require that information), perhaps I can somehow use JSON.stringify to send that object to the PHP script that processes the form and use json_decode to get the correct data structure on the server side without the hassle. In fact, I guess I could even do that with another Ajax call that is made when the user clicks on the submit button, instead of doing it through a regular form submission. But I don't suppose it's the best practice and, since I don't have much experience in web development, I want to know what's the best practice to a form with a complex structure dynamically generated in Javascript to a PHP script via the POST method.

EDIT: Just to clarify, since Bilel pointed out I didn't say what I'm planning to do with the data in the form, the PHP script on the server side is going to store the data in the database in a way that preserves the structure.

1 Answer 1

1

That's a detailed Question but you didn't told us How are you going to use these collected Data ?

If it's meant to be stored and displayed, then yes you already found the easiest solution by encoding $_POST data with json.

If for example, you could later need relational functionalities like querying User Ages (those being posted through input fields), then you should think about pre-structuring your data. With jQuery/Javascript functions first into a well formatted Json and later Parse the json on the server side to Insert each input field in it's appropriate Database field.

Even, it's against design conventions and space consuming, I do sometimes store the whole json in a separate field near other structured database records. New DBMS can handle json types...

Just to show you an example, I made this function to store a pre-structured json containing Room Information in a booking system, where we can dynamically add extra rooms:

function jss(){
    var json = {};
                json.rooms = $('.camera').map(function() {
            return {               

                max : $(this).find(".max").val()
              , arrange : $(this).find(".arrang").val()
               ,kids: $('[name^=enf]', this).map(function() {
                    return {
                        age: $(this).val()
                    };                    
                }).get()
               , adults: $('[name^=pers]', this).map(function() {
                    return {
                        name: $(this).val()

                    };                    
                }).get()
            };
        }).get();

        return JSON.stringify(json, null, "\t");
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I added a note in the question to explain what the PHP script on the server side was going to do with the data, namely store it in the database and also display it now that I think about it. But I'm still not sure how to send the Javascript object in which I store the data, encoded with json, to the server. I'd rather not add a field in the form to store the whole json-encoded object, so how else can I send it to the PHP script upon submission of the form?
I've never had issues when adding hidden fields to forms ! But if it matters, you can send json data using Ajax ;)
Thanks. As I said in my question, I thought of doing that, but I was assuming for no particular reason that it was not considered best practice. I guess I will just do it now that I'm reassured it's not considered a hack :-)
Here in a similar situation, I'm sharing an explanation of this method with a StackOverflow user : stackoverflow.com/questions/59814416/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.