I want to execute any JavaScript function that is part of a JSON using eval() but obviously I can’t do it right, and can’t figure out where exactly is the mistake/s. I’m using two very simple files, just for trying – the first is index.php and is at it is:
<!DOCTYPE html>
<html>
<head>
<title>Simple form sending and receiving a JSON object to/from PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var data =
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
var dataString = JSON.stringify(data);
$.post('simpleformSubmi.php', { data: dataString}, showResult, "text");
});
function showResult(res)
{
var data = eval('(' + res + ')');
$("#fullresponse").html("Full response: " +data);
}
</script>
<div id="fullresponse"></div>
</head>
<body>
and the second one is simpleformSubmi.php :
<?php
$logFile = 'logFile';
$res = json_decode(stripslashes($_POST['data']), true);
$arr = "function(){alert('Hi')}";
echo json_encode($res);
echo json_encode($arr);
So what I expected was after executing echo json_encode($arr); to get and alert but instead I get a mistake, and in Firebug the console shows error “missing ) in parenthetica”. So the question is – how to send a valid JS function this way and to execute it properly?
Thanks
Leron
Why you are
json_encodeing $arr. You may just return it as a stringecho $arrandeval('(' + res + ')()')in the JavaScript (notice the()in the JS to execute the function). You may need to removeecho json_encode($res)just to get this to work for now.