If I want to send an array from PHP to JavaScript, I do something like this with PHP:
<?php
$json=array();
$json['datetime']="Something";
$json['timestamp']="Something else"
$encoded=json_encode($json);
die($encoded);
?>
And this on jQuery/JavaScript (using Ajax):
...
success: function(response){
var chat = jQuery.parseJSON(response);
datetime=chat['datetime'];
timestamp=chat['timestamp'];
...
I was about wondering about doing the opposite.
In jQuery i have this array:
data_send['username']=$(".chat_username").val();
data_send['message']=$(".chat_message").val();
I want to encode this array as a JSON object, send this object via Ajax, and then take this object from $_POST/$_GET and decode it to an array.
How can I do this?
If you want to encode an array into JSON from Javascript you can use
JSON.stringify(myarray).However, you shouldn’t do that to send it to a PHP script.
jQuery has built in support for passing a map of key-value pairs in a POST method – just pass it as the
dataparameter in$.ajax()or as the second parameter to$.post().jQuery will then correctly URI encode any unsafe characters that appear (whether in keys, or values), so in your case you can use:
PHP then has built in support for reading that map – it’s
$_POST: