Reputation: 381
I'm currently lookong for a proper way to get add additional data (especially an array) to serialized data from a form and access it via PHP later on. I tried a lot, but nothing really worked.
For Instance:
HTML:
<form id='addUserForm'>
<input type='text' name='firstname'>
</form>
JS/JQUERY:
var testArr = {
one: "1",
two: "2",
three: 3
};
var ser = $("#addUserForm").serializeArray();
ser.push({ newArr:testArr});
console.log(ser);
$.ajax({
type: "POST",
url: url,
data: ser,
});
I used serializeArray() and pushed a new array to the serializedArray. When I console.log -> it works fine. But when I am trying to access it on PHP like:
var_dump($_POST);
I get:
array(2) {
["firstname"]=>
string(6) "123123"
["undefined"]=>
string(0) ""
}
It says that it is "undefined", even though via console.log in JS, the push was succesful.
Also I tried to convert it to a JSON string, with JSON.stringify(ser)
and data: {ser:ser}
-> which works, but it is more than awkward to access it.
I want to access it on PHP with $_POST['firstname']
and $_POST['testarr']
instead of $_POST[0]['value']
.
I hope it makes sense. So long story short: How can I add additional data / array to a serialized string and access it properly on PHP later on?
Upvotes: 2
Views: 1405
Reputation: 962
Try with this. Replace:
ser.push({ newArr:testArr});
with this:
for (var prop in testArr) {
ser.push({name: prop, value: testArr[prop]});
}
What we're doing here is creating an array of objects, each containing a name and value properties.
Upvotes: 1