I have a PHP variable which contains a JSON object in string format.
<?php
$url = "http://ip-api.com/json";
$phpObj = file_get_contents($url);
?>
Javascript:
<script>
var obj = "<?php echo $phpObj; ?>";
</script>
When I try to echo a PHP variable in javascript, I get the following error:
Uncaught SyntaxError: Invalid or unexpected token.
I've tried using json_encode, but it gives me the same error.
No need to use the quotes ("s) and json_encode as it is already a JSON object. Try
var obj = <?php echo $phpObj; ?>;
When I ma fetching the data and try -
<?php
$phpObj = file_get_contents("http://ip-api.com/json");
?>
<script>
var obj = <?php echo $phpObj; ?>;
console.log(obj);
</script>
I am getting -
{as: "AS45194 Syscon Infoway Pvt. Ltd.", city: "Thane", country: "India", countryCode: "IN", isp: "Syscon Infoway Pvt.", …}
in the console.
Passing simple arrays or arrays of objects between PHP and JavaScript can be done through json_encode and json_decode respectively. For instance, in your case, I can do the following
<?php
$url = "http://ip-api.com/json";
$phpObj = file_get_contents($url);
?>
<script>
var obj = <?php echo $phpObj; ?>;
</script>
Since the data fetched is JSON.
However, this fully depends on your application. If $phpObj = file_get_contents($url); returns json then I will simply do the following
<script>
var obj = <?php echo $phpObj; ?>;
</script>
If it's an object that is returned($phpObj), then I will, first of all, convert the object to an array then parse it into JSON format then echo it to JavaScript as shown below
<script>
var obj = <?php echo json_encode((array)$phpObj); ?>;
</script>
If it's an array that is returned, then I will parse the variable to JSON format then echo it to JavaScript as shown below
<script>
var obj = <?php echo json_encode($phpObj); ?>;
</script>
For the case of json_decode, if for instance, you want to use the value returned by file_get_contents($url); and assuming this returns JSON, you can convert the JSON to a PHP array or a PHP object as shown below,
$data_obj = json_decode($phpObj); //Return object not array
$data_arr = json_decode($phpObj,true); //Return array not object
Related
I am trying to set a javascript variable to be equal to the output of php code:
var name = '<?php global $email; echo json_encode(passthru("python Backend/User/getName.py $email"));?>';
When this runs, it returns the correct value, but it also attaches a null value to it:
var name = 'name
null';
This causes the code to take the value as null and not as the name returned.
As stated, passthru returns null on success and false on failure.
What you are looking to get is the content of the file so a simple way to do it is to just use output buffering.
You can have a simple function to return the value of your script like so:
<?php
function getPassthruValue(string $command)
{
ob_start();
passthru($command);
$returnValue = ob_get_contents();
ob_end_clean();
return $returnValue;
}
global $email;
$value = getPassthruValue("python Backend/User/getName.py $email");
?>
<script>
var passthruValue = "<?= $value ?>"
</script>
<?= === <?php echo just incase you didn't know what the shorthand annotation means.
This will grab the value of your python script and then set it to a js value.
This will return an empty string on failure so you may need to put some exception handling in depending on your needs.
So I am currently doing some coding for the website of someone of my outer family and I had to create a bar chart and now I need to fill it with data from their SQL-Database. First I just echo'd the array like this:
PHP:
<?php
$exampleArray = ["212", "33", "7"]
?>
and JS:
<script> var jExampleArray = <? echo json_encode($exampleArray);?>; </script>
And then I used jExampleArray in my bar chart code. Now I was very happy but the they say that it needs to be more secure (it involves their company) and I have to find a way to make sure nobody can just see the data while looking through the code on the page. I thought about using Ajax and what not but it just didn't work for me. I got it to alert me the array, but was not able to fill a Javascript array with it.
I never did stuff with JS, PHP oder SQL before and only learned Java in school so I am pretty clueless and most of the stuff I did was with help of the Internet. Luckily I managed to at least understand the code I wrote/copied.
Edit: [] for a JS array not {}
Your syntax for creating the PHP array is incorrect.
Use the function json_encode to transform PHP arrays into Javascript arrays and objects.
<?php
$arr = ['hello', 'world', 'foo', 'bar'];
$obj = ['hello' => 'world', 'foo' => 'bar'];
echo 'var Array = ' . json_encode($arr) . PHP_EOL .
'var Obj = ' . json_encode($obj, JSON_FORCE_OBJECT) . PHP_EOL;
Will result in the following:
var Array = ["hello","world","foo","bar"]
var Obj = {"hello":"world","foo":"bar"}
Some pseudo code to show how you might accomplish the stated goal
$data=array();
while( $rs=$db->fetch() ){
$data[]=array(
'field_1' => $rs->field_1,
'field_2' => $rs->field_2,
'field_3' => $rs->field_3
);
}
$json=json_encode( $data );
<script>
<?php
echo "var jExampleArray={$json};";
?>
/* rest of barchart code */
</script>
If the PHP array is available at page load use:
<?php
$phpArray = array('data1' => 2, 'data2' => 3);
?>
<script>var arr = <?php echo json_encode($phpArray); ?>;</script>
To retrieve PHP array in JS after page load using ajax:
var arr = JSON.parse(responseArray);
I've looked through various other questions on SO, but can't quite get the right answer. Basically, I have an array that needs data from a MySql database. Here's what I've tried:
var $name = "Foo",
$x = 10,
$bar =
<? php
$barQuery = mysql_query("SELECT item FROM table WHERE name = '$name' AND number = '$x'");
$barArray = array();
while ($r = mysql_fetch_assoc($barQuery))
{
$barArray[] = $r['item'];
}
echo json_encode($barArray);
?>;
EDIT: I then post this to a .php file, and print the returned data:
$.post("file.php", {bar: JSON.stringify($bar), name: $name}).done(function(data)
{
$('body').html(data);
window.print();
setTimeout("location.reload(true)", 500);
});
However, I get an error saying "syntax error, unexpected T_VARIABLE". Is it not possible to populate a JS array this way, or is there another way to do it?
var $name = "Foo",
$x = 10,
$bar = "
<?php
$barQuery = mysql_query("SELECT item FROM table WHERE name = '$name' AND number = '$x'");
$barArray = array();
while ($r = mysql_fetch_assoc($barQuery))
{
$barArray[] = $r['item'];
}
echo json_encode($barArray);
?>";
You have a superfluous space inside the PHP opening tag:
<? php
^--- this shouldn't be there
As it stands, the <? is parsed as a short open tag, and so the php is parsed as a(n undefined) constant, which is immediately followed by $barQuery—hence the syntax error that you see: unexpected T_VARIABLE.
I am doing a project on converting a database using sql, php and java for making a website. I have this inside my database:
echo's echos
sound wall
this is my code:
var places = [<?php
$mysqli = new mysqli("localhost", "root",null, "cdcol");
$stmt = $mysqli->prepare("select Name,Latitude,Longitude from food");
$stmt->execute();
$stmt->bind_result($name,$lat,$lon);
$space="
";
while ($stmt->fetch()) {
echo "['$name',$lat,$lon,$i,'Food',20],$space";
$i++;
}
$stmt->close();
$mysqli->close();
?>];
and using php, I have make I've taken out the two data but it has cause the problem with the '
the data display before will be
var place = [['echo's echos', lat, lon, 13, 'Food', 20],
['sound wall', lat, lon, 13, 'Food', 20]];
which the array will be use for some purposes
Try loading the values in php array using
array_push
Then pass the array as json encoded format, use json_encode
so the assignment to place will be made as
var place = <?php echo json_encode($placearray); ?>
Hope it helps!
your result looks like JSON, so you could put all your variables into a PHP array and let json_encode() do the escaping for you:
$placesJson = array();
while ($stmt->fetch()) {
$placesJson[] = array($name, $lat, $lon, $i, 'Food', 20);
$i++;
}
$places = json_encode($placesJson);
...
$php_array = mysqli_fetch_all($result,MYSQLI_ASSOC);
?>
<script type='text/javascript'>
<?php
$js_array = json_encode($php_array);
echo "var location = ". $js_array . ";\n";
?>
</script>
How can I modify the above code that gives me this output (an array of objects methinks?)
var javascript_array = [
{"city":"Hermosa Beach","lat":"33.860069","lng":"-118.398784"},
{"city":"San Jose","lat":"34.694628","lng":"-118.398784"},
.... ]
to give me this... (an array of arrays?)
var javascript_array = [
["Hermosa Beach",33.860069,-118.398784],
["San Jose",34.694628",-118.398784],
.... ]
without a bunch of foreaching's...
Use MYSQLI_NUM instead of MYSQL_ASSOC when you call mysqli_fetch_all(). Then the rows will be indexed arrays instead of associative arrays.
Although I don't know why you would want the array to be like this. Arrays should be used for uniform data, objects should be used for heterogeneous data.
thanks, this works and is very lean...
<?php
$query = "SELECT * FROM file";
$result = $con->query($query);
// Fetch all rows and return the result-set as an associative array:
// using numeric keys for the array, instead of creating an associative array.
$php_array = mysqli_fetch_all($result,MYSQLI_NUM);
?>
<script type='text/javascript'>
<?php
// create a JSON representation of a value that javascript will understand
$js_array = json_encode($php_array);
// dump json object into javascript variable 'locations'
echo "var locations =" . $js_array . ";\n";
?>
</script>