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 string echo $arr and eval('(' + res + ')()') in the JavaScript (notice the () in the JS to execute the function). You may need to remove echo json_encode($res) just to get this to work for now.
You can't. A JSON object cannot contain functions, only values.
You will have to setup some sort of webservice that actually prints JavaScript, which you in turn can call through a <script src="/your/endpoint"></script> declaration client side.
You can send the js function as data.
$data = array("something"=>"12345");
$js = "alert('hi!')";
$data["autoexec"] = $js;
echo json_encode($data);
Then on the clientside do something like eval(data["autoexec"]);
Related
Hi friends can anyone me for this plz. im new to this chapter..i am trying to get JSON format value from PHP but while im running i got this output "SyntaxError: JSON.parse: unexpected characte".. i think i had done mistake in php conversion ...plz help me friends
my .html file
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<title>Display Page</title>
</head>
<body>
<button type='button' id='getdata'>GetData.</button>
<button type='button' id='get'>sample</button>
<script type='text/javascript'>
$('#get').click(function() {
alert("laksjdflk");
});
$(document).ready(function() {
$('#getdata').click(function() {
$.ajax({
url:'neww.php' ,
dataType:'json' ,
success:function(output_string) {
alert(output_string);
},
error:function(xhr,ajaxOptions,thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
});
});
</script>
</body>
</html>
generatephp.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("androidlogin");
$sql=mysql_query("SELECT* FROM trysave");
$temp="";
$i=0;
while($row=mysql_fetch_assoc($sql)){
$temp=$row['stringss'];
$temp.=$row['integerr'];
$array[i]=$temp;
i++;
}
echo json_encode($array);// this will print the output in json
?>
This may because of Undefined array variable notice you have to define array in case no records found
Also you missed a $ before variable i which gives error(treated as CONSTANT, and which is undefined in your code), i should be $i like,
$array=array();// define here to prevent from "Notice"
while($row=mysql_fetch_assoc($sql))
{
$temp=$row['stringss'];
$temp.=$row['integerr'];
$array[$i]=$temp;// use $ before i
$i++;// use $ before i
}
echo json_encode($array);// this will print the output in json
One more thing you have mentioned PHP file name as generatephp.php and you are using url:'neww.php' , in $.ajax(), you have to check your code once.
Obvious problems (cough MySQL_*) aside, your PHP file should specify in the response headers that the output will be of type JSON. The output defaults to text/html and Javascript cannot parse it as a valid JSON object.
You can do it like this
<?php
header('Content-type: application/json');
// Rest of the code remains intact
i wold use something different ...
php:
<?php
mysql_connect("localhost","root","");
$sql=mysql_query("SELECT stringss, integerr FROM androidlogin.trysave");
$temp=array();
$i=0;
while($row=mysql_fetch_assoc($sql)){
$temp[] = $row;
}
echo json_encode($temp);// this will print the output in json
?>
//you do not need the $i variable since you will get in java str.length = that $i
<script type='text/javascript'>
$('#get').click(function() {
alert("laksjdflk");
});
$(document).ready(function() {
$('#getdata').click(
function() {
jQuery.getJSON( "neww.php") //no get vars
.done(function(a) {
//console.clear();
console.log(a);
show_data(a);
})
.fail(function(a) {
console.log( "error" );
});
});
});
function show_data(a){
for(var i=0; i<a.length; i++)
var stringss = a[i].stringss;
var integerr = a[i].integerr;
var nuber_temp = i;
//do stuff with them ...
}
</script>
if problem persists ... try http://php.net/manual/ro/function.urlencode.php
I'm making an aplication with phonegap and I'm stuck trying to send JSON data from the PHP on the server to JavaScript on the device. I want to do something like:
var JSON = '{ "Table" : ' + "http://www.hel.net/LoadDB.php=?table=exhibitions" + '}';
the php works fine and returns somethig like:
"[{"id":"1","name":"Art for everyone","image":null,"name2":"June 29, 2013: 11:00am.","description":"With reservation\r\nFree entrance","description2":null}]"
I want that result in a javascript variable to work later with:
var obj = eval ("(" + JSON + ")");
document.getElementById("rName").innerHTML=obj.Table[1].name;
document.getElementById("lname").innerHTML=obj.Table[1].name2;
What I want to do is something like:
var JSON = '{ "Table" : ' + "http://www.hel.net/LoadDB.php=?table=exhibitions" + '}';
var obj = eval ("(" + JSON + ")");
document.getElementById("rName").innerHTML=obj.Table[1].name;
document.getElementById("lname").innerHTML=obj.Table[1].name2;
How can I make the first line work? is it possible to make the first line work?
PS. I do not have much experience with JSON arrays.
Ok I tried ajax and works, I used:
console.log("before");
var jqxhr = $.ajax( "http://www.hel.com/LoadDB.php?table=exhibitions" )
.done(function(data) { console.log(data); })
.fail(function() { console.log("error"); })
.always(function() { console.log("complete"); });
console.log("after");
more info in:
api.jquery.com
I think all you need is var obj = <?php echo $myjsonencodedvar; ?>
or
var obj = <?php echo json_encode($myarray_or_object); ?>
Since I said "I think..." I decided to test it out. I found the following dump() function here on SO.
$arr=array(1,'biscuit'=>'gravy',3,4,5);
$json=json_encode($arr);
?>
<script>
j=<?php echo $json; ?>;
document.write(dump(j));
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
return out;
}
</script>
output:
0: 1 biscuit: gravy 1: 3 2: 4 3: 5
Try this:
PHP: (json.php)
<?php
header("Content-Type: text/json");
//the data format your question mentioned
$data = array("Table"=>array(array("id"=>"1","name"=>"Art for everyone","image"=>null,"name2"=>"June 29, 2013","description"=>"With reservation\r\nFree entrance","description2"=>null)));
echo json_encode($data);
?>
Front-end:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$.get("json.php",function(json){
alert(json.Table[0].name);
});
</script>
</body>
</html>
Hope this is helpful for you.
using JSONP (no callbacks), and on the client side use $.getJSON() it will parse it from json string to js object.
I have a php code that provides the database values. I need those values in the javascript variable.
Javascript Code
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script type="text/javascript">
function text() {
var textVal=$("#busqueda_de_producto").val();
$.ajax(
{
type:"POST",
url:"index.php", //here goes your php script file where you want to pass value
data: textVal,
success:function(response)
{
// JAVSCRIPT VARIABLE = varable from PHP file.
}
});
return false;
}
</script>
PHP FILE CODE:
<?php
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo'];
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
?>
Your returning data is in the response parameter. You have to echo your data in PHP to get the results
Using JSON format is convenient
because of its key-value nature.
Use json_encode to convert PHP array to JSON.
echo the json_encoded variable
you will be able to receive that JSON response data through $.ajax
JavaScipt/HTML:
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script type="text/javascript">
function text()
{
var textVal=$("#busqueda_de_producto").val();
$.post('index.php', { codigo:textVal }, function(response) {
$('#output').html(response.FIELDNAME);
}, 'json');
return false;
}
</script>
<span id="output"></span>
PHP:
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo='".mysql_escape_string($_POST['codigo'])."'";
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
echo json_encode($row11);
You aren't echoing anything in your PHP script.
Try altering your PHP to this:
<?php
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo'];
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
echo $row11; //This sends the array to the Ajax call. Make sure to only send what you want.
?>
Then in your Ajax call you can alert this by writing alert(response) in your success handler.
Tips
Send your data to the server as a URL serialised string : request=foo&bar=4. You can also try JSON if you fancy it.
Don't use mysql_* PHP functions as they are being deprecated. Try a search for PHP Data Objects (PDO).
i see lots of things that needs to be corrected
the data in your ajax do it this way data: {'codigo':textVal}, since you are using $_GET['codigo'], which leads to the second correction, you used type:"POST" so you must also access the $_POST variable and not the $_GET variable and lastly the target of your ajax does not display / return anything you either echo it or echo json_encode() it
The best solution is to use
echo json_encode("YOUR ARRAY/VALUE TO BE USED");
and then parse JSON in the javascript code as
obj = JSON.parse(response);
I want to localize my webapp. Since localization through javascript only is not recommended I thought using php would be an alternative.
So with php I read a messages.json file that stores all localization data.
$json = file_get_contents("_locales/en/messages.json");
In the header of my webapp I generate some javascript with php according to the user's browser language.
echo "var localeObj = " . $json . ";";
So this is just a var that holds all data from the messages.json file that looks like that
{
"extTitle": {
"message": "Test1"
},
"extName":{
"message": "Test2"
}
}
Now I want to be able to access each item from the json like
var title = getItem("extTitle");
and it returns Test1. Any idea how to do that?
I am not very familar with json but if I just alert the localeObj it gives me just [object Object].
var getItem = function(item) {
return localObj[item].message;
};
You could always encapsulate your i18n strings too...
(function() {
var localObj = { ... };
window.getItem = function(item) {
return localObj[item].message;
};
})();
This way, no other variables can possibly clobber your localObj.
You use array syntax [], or dot syntax ., to access javascript object properties.
Example:
localeObj["extTitle"];
localeObj.extTitle;
I would recommend reading something like this to get more familier with JSON.
You can initialize javascript variable like this.
var json = eval(<? echo $json ?>);
alert(json.extTitle.message+ ' '+json.extName.message);
Inside messages.php:
<?php
header('Content-type:application/javascript');
$messages = array(
"yes"=>"hai",
"no"=>"iie"
);
$messages = json_encode($messages);
echo "window.messages = $messages";
?>
Inside index.html:
<html>
<body>
<script type="text/javascript" src="messages.php"></script>
<script type="text/javascript">
console.log(window.messages)
</script>
</body>
</html>
As long as you tell the browser to interpret the php file as a javascript file, you can echo anything you want.
I finally succeeded in using Ajax to get SOMETHING sent from one page to another! What I'm trying to do is pass an array from a PHP file to a Javascript file, and the Javascript file is receiving this in this.responseText:
<html>
<head>
<script type="text/javascript">
var jsonArray = ["chickens","horses","cows","werewolves","zombies","vampires","phantoms","U.S. Congressmen","performance artists","pieces of fencepost","barnhouses","robots","cyborgs"]
</script>
</head>
</html>
I tried running eval() and alerting the result, but no result appears. How do I successfully extract the array from this.responseText?
Edit Here is my function thus far:
/*
* Function: selectVictim
* Called from function laserOn()
*
* Selects a random victim from a list of victims
*
* #return String: victim
*/
function selectVictim()
{
var params = "url=queenofsheep.com/Sheep/victims.php";
var request = new ajaxRequest();
request.open("POST", "victims.php", true);
request.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
request.setRequestHeader("Content-Length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function ()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null )
{
var vicArray = eval('('+this.responseText+')');
var numVic = Math.floor(Math.random() * (vicArray - 1));
alert(vicArray);
}
else alert("Ajax error: No data received");
}
else alert("Ajax Error: " + this.statusText);
}
}
request.send(params);
}
Second Edit The file containing the array (in PHP) is as follows:
<html>
<head>
<?php
$victims = array(
// Animals
"chickens",
"horses",
"cows",
// Supernatural
"werewolves",
"zombies",
"vampires",
"phantoms",
// Human
"U.S. Congressmen",
"performance artists",
// Inanimate, non-mechanical
"pieces of fencepost",
"barnhouses",
// Mechanical
"robots",
"cyborgs"
);
?>
<script type="text/javascript">
var jsonArray = <?php echo json_encode($victims); ?>
</script>
</head>
</html>
If your php page is returning all the text that you reported (with <html> etc...) then your output is not a JSON object, but an html page. Your response should contain only your serialized JSON object (and the proper http response headers)...
Once you have 'cleaned' your output you can use JSON2 library to parse your object:
http://www.json.org/js.html
var myObject = JSON.parse(myJSONtext);
That does not look like a proper JSON response from the server, because it contains HTML code and then a chunk of javascript. The response should contain only javascript code containing data, like
var data = ["chickens","horses","cows","werewolves","zombies"]";
You can then eval() the string and it will work.
As said above, eval() might be unsafe, so, if using jQuery, you can use the $.parseJSON function which is safe.
To return the JSON correctly, don't output HTML at all in the page, just do something like
<?php
$victims = ...; // fill array
echo json_encode($victims);
?>
You can use the library on json.org or use eval("(" + this.responseText + ")");
Generally you want to use a library to parse the JSON string instead of eval because eval is generally unsafe.