Reputation: 443
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.
Upvotes: 1
Views: 603
Reputation: 12808
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.
Upvotes: 2