0

I'm trying to convert a returned json object into a serialized string that I can process further with some PHP server side code:

The returned object looks like this:

Object {id: "123456787654321", email: "some-email@gmail.com", first_name:   "First", gender: "male", last_name: "Last"}

I can convert the object to a string with the following:

var paramString = JSON.stringify(response);
console.log(paramString);

// doesn't work
//var params = paramString.serialize();

How do I now convert the string to a serialized string that I can pass to my server with the following client side call:

I would expect something like this:

id=123456787654321&email=some-email@gmail.com&first_name...

My server side code:

$.post("/functions/test_functions.php", {params: params}, function(data) {
    ...                             
}, "json");

I handle the params array like this server side:

$vars = $_SERVER['REQUEST_METHOD'] === "GET" ? $_GET : $_POST; 

$params = array();
isset($vars['params']) ? parse_str($vars['params'], $params) : null;
Paul
  • 11,671
  • 32
  • 91
  • 143

2 Answers2

0

You can pass JSON-string to server and decode it with json_decode(). See http://php.net/manual/en/function.json-decode.php for details.

Max Zuber
  • 1,217
  • 10
  • 16
  • I don't want to introduce another decoding method server side for my params string. All my other functions pass a serialized string that I can parse into an array – Paul Mar 16 '15 at 13:36
0

Unless there's a specific reason for stringifying, you don't actually need to. jQuery .post will handle the serialization for you, for example:

var response = {id: "123456787654321", email: "some-email@gmail.com", first_name:   "First", gender: "male", last_name: "Last"};
$.post("/functions/test_functions.php", response, function(data) {
    ...                             
}, "json");

Will make a POST request like this:

/functions/test_functions.php
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Form Data: id=12345654321&email=some-email@gmail.com&first_name....

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176