1

I want to know why we need to serialize a JavaScript Object before sending to the server.

Example:

var send_data= {
    id : 10,
    name : 20,

    school : {
       name : "xyz",
       location : "some place"
    }
}

If I send this data without serializing, using ajax like this

$.ajax({
    type: "POST",
    url: "some.php",
    data: { "info" : send_data}
})

Is there something wrong with this code? Because I can access all the data without unserializing...

$data = $_POST["info"];
echo $data["school"]["name"];
7
  • There's nothing wrong with the way you're sending it in the example. Commented Feb 12, 2014 at 13:40
  • Use JSON.Stringify if you are sending data to Server and if you are getting data from Server use JSON.Parse Commented Feb 12, 2014 at 13:45
  • @ArpitSrivastava: Not necessary. The data parameter the OP uses works just fine. Commented Feb 12, 2014 at 13:48
  • @Cerbrus:But it's a good practice we should use in order to check weather we are right dict or JSON to server because the way user handling post data. Commented Feb 12, 2014 at 13:50
  • @ArpitSrivastava: You know jQuery serializes the data parameter, internally, right? And what are you talking about the weather for? Commented Feb 12, 2014 at 13:58

1 Answer 1

1

The data MUST be serialized, because network traffic consists of series of bytes. At some point, your data structures must be turned into something that can be sent over a network.

However, jQuery's .ajax() function already does serialization if you use an object instead of a string for its data argument. So no need to do it there.

I don't know PHP well but if the code you have there works, then apparently PHP also automatically unserializes the data.

So I'd say that yes, serializing is necessary, but doing it the way you describe actually does serialize it in the background.

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

1 Comment

Thanks a lot Remco. I was so confused that I started to think, that browser is serializing that for me... and then I started to think about cross browser compatibility.. Thanks a lot :)

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.