ajax - Passing php objects to $.post() -
i pass 2 php objects data, are, $.post.
$(function() { $("button").click(function() { $.post("fight.php",{player: "<?php $player;?>", enemy: "<?php $enemy; ?>"},function(result) { $("#displayfight").html(result); }); }); }); $player, $enemy 2 different objects few properties each. pass them whole objects are, fight.php can deal them.
i've tried serialize, no avail:
{player: $("<?php $player ?>").serialize()} how can this?
note: methods i've tried, either 'unknown identifier' or $_post comes out empty on receiving page.
edit: json_encode part works, decoding fails. on receiving page:
$player = json_decode($_post["player"]) fails , returns error: json_decode() expects parameter 1 string, array given
you need use json_encode, this:
$.post("fight.php",{ player: <?php echo json_encode($player);?>, enemy: <?php echo json_encode($enemy);?> }, ... ); note there no quotes around <?php ?> tags; json_encode add them automatically if required.
apart that, need aware of requirements json_encode imposes: importantly, if objects contain string content (either property or property of sub-objects) these strings must encoded in utf-8.
Comments
Post a Comment