Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

serializing a JSON data packet in a jQuery Ajax POST

Tags:

json

jquery

ajax

I have a data structure like socket

var s = {
    "a": "foo",
    "b": 5,
    "c": {"d": "a long string"},
    "e": {
        "f": {
            "g": {
                "h": [1, 0, -2.1, 1.43]
            }
        },
        "i": {
            "j": {
                "k": [-3.2, 3.003, 0, 0]
            }
        }
    }
};

I want to store the "a", "b", "c", and "e" keys of variable s in a database table so I can reconstruct them back again. I am sending s via a jQuery Ajax POST. The values would be inserted and stored as just plain text (except for "b" which is always a number).

ajax: {
    url: uri,
    type: "POST",
    data: s,
    dataType: "json",
    success: function(data, status) { .. }
}

Here is the problem I am encountering. In Firebug I can see my post parameters… they are really messed up. Seems like the data have been serialized at the level of each element (kinda like a deep serialization) while I was hoping for something like

e={"f":{"g":{"h":[1,0,-2.1,1.43]}},"i":{"j":{"k":[-3.2,3.003,0,0]}}}

Update: Instead, I am getting the following (I have unescaped the string below so it is more readable)

a=foo&b=5&c[d]=a long string&e[f][g][h][]=1&e[f][g][h][]=0&e[f][g][h][]=-2.1&e[f][g][h][]=1.43

Perhaps I am doing this the wrong way, so feel free to guide me to a better way.

like image 492
punkish Avatar asked Jan 26 '12 03:01

punkish


1 Answers

Use JSON.stringify method to serialize the data object into string and post it. On the server side just store this as is in your DB. Try this

ajax: {
    url: uri,
    type: "POST",
    data: { data: JSON.stringify(s) },
    dataType: "json",
    success: function(data, status) { .. }
}

Almost all the modern browsers support JSON natively. For browsers which do not have it natively you can include the required js from http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js

like image 89
ShankarSangoli Avatar answered Nov 12 '22 07:11

ShankarSangoli