1

I have a dynamic built with jQuery UI form where user can add new items in the form. I am trying to save them in my MySQL database as JSON. But with my current approach, only the last item of the form is being saved. How can I loop the array for each item from the POST values? My form is sending data as:

item_sl: 1
item_id: 14044
item_sl: 2
item_id: 14044

To prepare the data, I am using the following method. But as you can see, it doesn't loop for each item_sl. So, it is saving only the last values.

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $item_sl = trim($_POST["item_sl"]);
    $item_id = trim($_POST["item_id"]);

    foreach ($_POST["item_sl"] as $items) {
        $rxData['items'][] = array(
            'item_sl' => $items->item_sl,
            'item_id' => $items->item_id,
        );
    }
    $rxData = array(
        'item_list' => array()
    );
    $rxJSON = json_encode($rxData, JSON_PRETTY_PRINT);

    // MySQL insert
}

How can I prepare the array to loop for each item_sl and prepare the JSON array for inserting?

The form has become complicated due to jQuery Sortable. But I'm attaching it below for clarification:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" action="" method="post">
    <table id="sort" class="grid">
        <thead>
            <tr>
                <th class="index">No.</th>
                <th>Items</th>
                <th>Serial</th>
                <th>Item ID</th>
            </tr>
        </thead>
        <tbody id="add">
        </tbody>
    </table>
    <input type="submit" name="saveStay" value="Save" id="saveStay">
</form>
<script>
    $(document).ready(function() {
        var fixHelperModified = function(e, tr) {
                var $originals = tr.children();
                var $helper = tr.clone();
                $helper.children().each(function(index) {
                    $(this).width($originals.eq(index).width())
                });
                return $helper;
            },
            updateIndex = function() {
                $('td.index').each(function(i) {
                    $(this).html(i + 1);
                });
                $('input.indexInput').each(function(i) {
                    $(this).val(i + 1);
                });
            };
        $("#sort tbody").sortable({
            helper: fixHelperModified,
            stop: updateIndex
        }).disableSelection();

        $("#addNew").click(function() {
            var rx_text = $('#item_search').val();
            var item_id = $('#item_id').val();

            $('#add').append("<tr class='rem'><td class='index'>1</td><td>" +
                rx_text +
                "</td><td><input name='item_sl' class='indexInput' type='text' value='1'>" +
                "</td><td><input name='item_id' type='text' value='" +
                item_id +
                "'></td></tr>");
            updateIndex();
        });
    });
</script>
5
  • Why don't you send an array since you have multiple values for the same key? Commented Aug 17, 2021 at 13:44
  • @pr1nc3, I have updated the question with the form I'm working with. Can you please have a look? Commented Aug 17, 2021 at 14:15
  • Since you are working with array, you have to submit input as array <input name='item_sl[]"... Commented Aug 17, 2021 at 14:18
  • check this out stackoverflow.com/a/3314581/16039 Commented Aug 17, 2021 at 14:19
  • @vaske, Thanks, I have tried to submit using an array following your suggestion. But it is not returning any value. I have updated the question with the updated POST method. Can you please have a look if I am doing it in right way? Commented Aug 17, 2021 at 14:59

1 Answer 1

1

First, update the two input names as name='item_sl[]' and name='item_id[]'. These will post your values as array. Then loop the values and format them as JSON as required. For example, with the following loop,

$rxData = array(
    'items' => array()
);
foreach(item_sl as $key => $n) {
    $rxData['items'][] = array(
        'item_sl' => $n,
        'item_id' => item_id[$key]
    );
}

You will get a JSON structured as below.

{
   "items":[
      {
         "item_sl":"1",
         "item_id":"1234"
      },
      {
         "item_sl":"2",
         "item_id":"2345"
      }
   ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow! I appreciate your time. It is what I have been expecting to display.

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.