I created a jquery object via $("input").serializeArray();
This is my output:
0: Object { name: "id", value: "9" }
1: Object { name: "name", value: "Fred" }
2: Object { name: "quantity", value: "1" }
I send this object via ajax to my php page. There I get it via $_POST['myarray']. The output is:
[0]=>
array(2) {
["name"]=>
string(2) "id"
["value"]=>
string(1) "9"
}
[1]=>
array(2) {
["name"]=>
string(4) "name"
["value"]=>
string(14) "Fred"
}
[2]=>
array(2) {
["name"]=>
string(8) "quantity"
["value"]=>
string(1) "1"
}
But the output I would need is:
array(3) {
["id"]=>
string(1) "9"
["name"]=>
string(1) "Fred"
["quantity"]=>
string(1) "1"
}
asked Dec 13, 2017 at 15:18
peace_love
6,52314 gold badges88 silver badges187 bronze badges
2 Answers 2
To get the required data structure in PHP you need to send a single object from your JS code in this format:
{
id: "9",
name: "Fred",
quantity: "1"
}
To do that you can build a new object using the keys of the objects within the current array, like this:
var serializedForm = [
{ name: "id", value: "9" },
{ name: "name", value: "Fred" },
{ name: "quantity", value: "1" }
];
var o = {};
serializedForm.forEach((k) => {
o[k.name] = k.value;
});
console.log(o);
answered Dec 13, 2017 at 15:22
Rory McCrossan
338k41 gold badges322 silver badges353 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
On the server side, you can pick the key/value pairs in a loop and create the array format you desire:
$formObj = $_POST['myarray'];
$myObj = array();
foreach($formObj as $array){
$myObj[$array["name"]] = $array["value"];
}
var_dump($myObj); // New object with key/value pair
answered Dec 13, 2017 at 15:39
William
7492 gold badges13 silver badges21 bronze badges
Comments
default
$("input").serializeArray();did not create the object you'd like. It created an array of objects. Consolidate those objects on the client side.