dibs
dibs

Reputation: 1077

How best to pass a complex JavaScript object to PHP?

I have a JavaScript object that contains two arrays. One of the arrays is an array of objects and the other is just a straight forward array.

i.e.

obj = {
  arr1: [
    {
      a1: 'val',
      a2: 'val'
    },
    {
      b1: 'val',
      b2: 'val'
    }
  ],
  arr2: ['a', 'b', 'c']
};

I am trying to pass this whole lot as on object to PHP to store in a MySQL database. How best should I go about this so that I can eventually pass it back to JavaScript in the same structure as it started out as?

Many thanks for any help.

Upvotes: 0

Views: 114

Answers (1)

cocco
cocco

Reputation: 16706

JSON

Here is an example to convert an object into a string & back in javascript

it should not contain functions.

var obj={a:'a',b:'b',array:[1,2,3,4]};
var string=JSON.stringify(obj);

// or back to object 
var obj=JSON.parse(string);

POST that string.

Then in php you can do the same.

<?php
$obj=json_decode($_POST['string']);

// back to object
// $string=json_encode($obj);
?>

if you want a post example just ask.. or if you have any questions.

Upvotes: 2

Related Questions