I was wondering what the best way would be to pass a php object via AJAX.
for example
//objectClass = objectClass.php
$obj = new objectClass();
<a href="javascript:getOutput("some variable", $obj);
As the other file i.e. output.php (called through ajax in getOutput() function) needs to access objectClass.php as well, what is the best way to access $obj?
I tried to jscon_encode($obj) then decode but not working.
Thanks in advance
Honestly, it's going to be easiest to just store the information that needs passed (in this case an object) in a session variable like @mario suggested. If you need it to be a dynamically named session variable, you could just pass the name(string) of the session variable via AJAX.
json_encode is the best way.
You need to use ' instead of " for href argument, and add JSON_HEX_APOS option to json_encode to escape any ' in JSON.
Use it like this:
<?php
//objectClass = objectClass.php
$obj = new objectClass();
?>
<a href='javascript:getOutput(<?php echo $some_variable ?>,<?php echo json_encode ($obj, JSON_HEX_APOS) ?>);'></a>
or
<?php
//objectClass = objectClass.php
$obj = new objectClass();
echo "<a href='javascript:getOutput($some_variable, " . json_encode ($obj, JSON_HEX_APOS) . " );'></a>"
?>
EDIT: If you have jQuery, I recommend using jQuery.parse () to load JSON. If not, you can use JSON.parse (), but I don't know if it's compatible with archaic browsers. Anyway you should be fine without them (just check for XSS on your server-side).