Well in my script I need to serialize an event object from javascript in JSON, and pass it to PHP since the server needs some of the information. However, it seems that javascript events are by default not serializable, as they contain circular references. So how can I serialize an event object to JSON? Anyone know what to do about this?
Better approach here would be to construct your own object filled with values of event object that you only need. Then you can serialize that object and send it.
var data = {
foo: event.foo,
bar: event.bar
};
var json = JSON.stringify(data);
Otherwise you will have huge overhead because event objects contain lot of information that you probably don’t need
I see, yeah it is a better idea to pass whatever properties I need from event to PHP through JSON, thanks. But I wonder, do you know what are the best way to pass event object to PHP? Of course, I know it must be done through AJAX, but through which method? The GET method seems to be a good idea, but it can result in very long query string which I dont like. The POST method can also be used, but its best suited for form submission only. I am also considering using a temporary cookie, but not sure if its a good idea. Ideally I can pass it to PHP’s $_GET array without polluting the query string, is this possible?
When I need to pass large object to PHP I usually convert it to JSON string and then send it as single POST variable. Like that:
//javascript
var json = JSON.stringify( largeObject );
$.post('backend.php', {json: json});
//php
$json = $_POST['json'];
$largeObject = json_decode($json, true);
This approach allows to restore object in PHP with single line of code
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.