1

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"
      }
3
  • 1
    $("input").serializeArray(); did not create the object you'd like. It created an array of objects. Consolidate those objects on the client side. Commented Dec 13, 2017 at 15:24
  • You can change js or make array by php. What are you prefer? Commented Dec 13, 2017 at 15:25
  • Oh ok, I understand. The problem is the object I created. Yes, I will try to figure out how I can created the object properly Commented Dec 13, 2017 at 15:26

2 Answers 2

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);

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

Comments

2

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

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.