1

i have a big form with lot of inputs. Also i have a javascript multidimensional array. It's an array of custom objects, that they are adding and removing as a shopping cart . The array is defined as a local JS variable. When i submit the form, i need to pass the array too, and i don't know how to do it. Here I leave an example, it's illustrative only , as my form and my classes are much more complex .

<SCRIPT LANGUAGE="JavaScript">
var itemList = [];

var CustomClass = function (id, description) {
            this.id = id;
            this.description = description;
          };

function addItem(id, description)
{
    var item = new CustomClass( id,description);

    itemList.push(item);
}

</script>

<form method="post" action="formSave.php">

<input type="text" name="someInput1">
<input type="text" name="someInput2">

<input type="submit" value="Submit">

</form>

Thank you very much.

1 Answer 1

2

If you were set on using a form to submit your data, id make a hidden text input and use JSON.stringify(data) in your js and decode it on server with json_decode server side.

<input id = 'jsValueHolder' style = 'display:none'>
<script>
    function loadJSDataBeforeSend(dataToSend){
         document.getElementById("jsValueHolder").value = JSON.stringify(dataToSend);
    }
    loadJSDataBeforeSend(itemList);
</script>

And on server side:

<?php
   /* other code */
   $jsonDataString = ... // get your data from the input
   $dataObject = json_decode($jsonDataString);
   $dataKeyValueArray = json_decode($jsonDataString, true);
?>

Note how adding true to the json_decode function returns a key value array rather than a php object.

Sign up to request clarification or add additional context in comments.

Comments

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.