0

I am trying to parse the form submitted hidden input text using a foreach loop.

<input type="hidden" id="snippet_tags" name="snippet_tags[]" value="["88","92","96","98"]">

Get this using the following function

$snippet_tags = json_decode($_POST['snippet_tags'], true);

and parse the values using foreach loop

foreach ($snippet_tags as $selectedOption){

                        $ins_snippet_tag_data = array(
                            'snippet_id' => $insertDataReturnLastId,
                            'tag_id' => $selectedOption,
                            'priority' => 1,

                        );

                 $this->Constant_model->insertDataReturnLastId('snippets_tags', $ins_snippet_tag_data);

                }

Here the problem is values of tag_id is not saving in database

1 Answer 1

1

You can't use the same quotes to delimit the value and the strings inside it. You need to use single quotes around the value.

<input type="hidden" id="snippet_tags" name="snippet_tags[]" value='["88","92","96","98"]'>

The way you wrote it, it's treated as if you'd written value="[" and the rest is ignored.

Also, since you have [] after the name, $_POST['snippet_tags'] will be an array, so you need to loop over it.

foreach ($_POST['snippet_tags'] as $json) {
    $snippet_tags = json_decode($json, true);
    foreach ($snippet_tags as $selectedOption){
        $ins_snippet_tag_data = array(
            'snippet_id' => $insertDataReturnLastId,
            'tag_id' => $selectedOption,
            'priority' => 1,
        );
        $this->Constant_model->insertDataReturnLastId('snippets_tags', $ins_snippet_tag_data);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

i am saving these like this - $('#snippet_tags').val(JSON.stringify(snippettags));
Are there more than one of these inputs? Usually you use array-style names when you have multiple inputs of the same kind.

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.