0

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.

6
  • 1
    You data can be easily represented as JSON. Commented Jan 29, 2014 at 23:50
  • @elclanrs Does the mixing of array and object not cause any issues with JSON? Is there anything I need to be aware of that might cause issues with this structure? Commented Jan 29, 2014 at 23:53
  • There are tons of resources on the web and in SO about how to do this (using JSON), you haven't done any research. -1 Commented Jan 29, 2014 at 23:54
  • 1
    @dibs as long as the data type is supported by JSON (objects, arrays, and strings, the only types in your example, are supported), it will work. JSON is meant to be easy to use like that. Commented Jan 29, 2014 at 23:55
  • @Markasoftware I thought I might be able to just use a JSON string but wanted to be sure this was the best way, so I have asked. Commented Jan 29, 2014 at 23:55

1 Answer 1

2

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.

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

4 Comments

Thanks @cocco. I was thinking this would be the way but wanted to make sure I wasn't missing anything/doing something that would not be advised.
it actually can include functions - JSON.stringify will just strip them out and you'll have to add them back in. Also no reason to json_decode - just save it as a string and serve it back with an application/json contentType
so basically ...it should not contain functions .. as it's useless.btw you can convert your functions. to base64 & use (new Function(base64))().but that is another story.
Just wanted to clarify that it won't throw an error or anything, functions are often used as a way of forcing json serializers to omit properties.

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.