How to Pass a PHP array to JavaScript function? - javascript

First of all, this question looks a duplicate of Pass a PHP array to a JavaScript function, but I actually used the first solution of Pass a PHP array to a JavaScript function - and it doesnt seem to work:
More specifically, the php echo line in the code below seems to create erroneous js output according to console error message( Uncaught SyntaxError: Unexpected token <); the console shows created html starting with "var s1 = <br />
<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1'..."
...while I'd expect a clean var s1 = [1,2,3,4,5,6,7,8,9] - the result I also see when I tested the echo line in ideone.com
Any idea why the echo line is creating this stuff, and how to fix this?
Related joomla php code:
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
$document = JFactory::getDocument();
//add jqplot libraries
JHtml::_('jquery.framework');
JHTML::script(JUri::root() .'media/system/js/jquery.jqplot.min.js');
//$document->addStyleSheet(JUri::root() .'media/system/js/jquery.jqplot.min.css');
JHtml::stylesheet( JUri::root() . 'media/system/js/jquery.jqplot.min.css' );
JHTML::script(JUri::root() .'media/system/js/jquery.jqplot.min.css');
JHTML::script(JUri::root() .'media/system/js/jqplot.barRenderer.min.js');
JHTML::script(JUri::root() .'media/system/js/jqplot.categoryAxisRenderer.min.js');
JHTML::script(JUri::root() .'media/system/js/jqplot.pointLabels.min.js');
JHTML::script(JUri::root() .'media/system/js/jqplot.enhancedLegendRenderer.js');
JHTML::script(JUri::root() .'media/system/js/weqlib.js');
$chartvals = array(1,2,3,4,5,6,7,8,9);
?>
<head>
<script type="text/javascript">
jQuery(document).ready(function(){
var s1 = <?php echo json_encode(chartvals); ?>; //!the echo seems to create erroneous js output accoding to console(?)
plot1 = jQuery.jqplot ('chart1', [s1]); //copied from example at
}); //$(document).ready
</script>
</head>

You forgot the $ to referrence the chartvals var at the json_encode() function call:
var s1 = <?php echo json_encode(chartvals); ?>;
Should be
var s1 = <?php echo json_encode($chartvals); ?>;
To not trap into this sort of mistakes again you can add error_reporting(E_ALL); to the beginning of your script and set display_errors to on in your PHP config during development.

var s1 = <?php echo json_encode($chartvals); ?>; //!the echo seems to create

Related

'unexpected token: identifier error' - assigning php json array type variable value to a javascript function from php code

I am trying to call JavaScript function in php and pass it value of a php json array type variable as an argument. I found from search on SO forum one way to do this is to echo/print_r the variable value to a js var inside a js script within php code. I am trying do it this way but I am not able to recover from 'unexpected token: identifier error ' while doing so.
I am trying to figure out the reason of syntax error but couldn't. I tried different ways what I found; by putting quotes single/double around php part within the script, without quotes as some places I found solution with quotes some places without but no one seems working.
Here is my code. It will be very helpful if someone sees it and point what is causing this error.
<script>
dspChrt(WData);
.......
</script>
<HTML>
<?php
$WData;
require("Connection.php");
try {
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $k=>$v) {
$WData = json_encode($v);
//print_r($WData);
}?>
<script>
var Wdata = <?php print_r($WData);?>
dspChrt(WData);
consol.log(WData);
</script>
<?php
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</HTML>
First of all you need to parse the JSON using JSON.parse.
Also you need to change the sequence of php and javascript code.
If you want to assign php data to Javascript variable, please retrieve data using php first and write javascript code below it.
For example :
<?php
$v = array(1,2,3);
$data = json_encode($v);
?>
<script>
var WData = JSON.parse('<?php echo $data; ?>');
dspChrt(WData);
</script>
You should encode your PHP into JSON to pass it to JavaScript.
And you should prepare your data first.
<?php
$data = array('xxx'=>'yyy');
?>
<script>
var data = <?php echo json_encode($data); ?>;
//then in js, use the data
</script>
for your code, there are too many errors to be fixed:
<HTML>
<?php
require("Connection.php");
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = array();
foreach($stmt->fetchAll() as $k=>$v) {
$WData[] = $v;
}
?>
<script>
var WData = <?php echo json_encode($WData);?>;
console.log(WData);
dspChrt(WData);
</script>
</HTML>

PHP: why two codes that echo the same string return different results?

I'm new at PHP and I don't understand why this happens.I try using echo to show "$imglinksis" and the result is exactly http://catpic.s3.amazonaws.com/product.jpg
I do not understand why the 2nd Code fails. Please help!
Code #1: This code completely works in returning the fields I want
<?php function CallCatpicAPI($photoUrl){do something...}
$imglinksis = "http://catpic.s3.amazonaws.com/product.jpg";
$jsonReturnCatpic = CallCatpicAPI($imglinksis);?>
Code #2: Fail to return: API says invalid URL image link
<?php function CallCatpicAPI($photoUrl){do something...}?>
<script>var img_link = "http://catpic.s3.amazonaws.com/product.jpg";</script>
<?php
$imglinksis = "<script>document.write(img_link).toString()</script>";
$jsonReturnCatpic = CallCatpicAPI($imglinksis);?>
You are mixing the two codes. Your php is executed on the server but the javascript is executed on the client side after php executed. You can fix your second code by this:
<?php
$imglinksis = 'http://catpic.s3.amazonaws.com/product.jpg';
function CallCatpicAPI($photoUrl){do something...}
?>
<script>var img_link = '<?php echo $imglinksis; ?>';</script>
<?php
$jsonReturnCatpic = CallCatpicAPI($imglinksis);
?>

javascript code malfunction when json encode is added

i have a html table and it has expandable row
but when i added json encode code to the javascript code. the html table row expand without the user interaction. when the page is loaded. it just expand. and i need to put the code in a sigle javascript because i need to use the data from other javascript function. hope my question is clear. sorry for my bad english
<script type='text/javascript'>//<![CDATA[
var tracknumberreceiveglobal;
$(document).ready(function(){
$("#report tr:odd").addClass("odd");
$("#report tr:not(.odd)").hide();
$("#report tr:first-child").show();
$("#report tr.odd").click(function(){
tracknumberreceiveglobal = $(this).closest("tr").find("td:eq(0)").text();
$(this).next("tr").toggle();
$(this).find('i').toggleClass('glyphicon-plus-sign').toggleClass('glyphicon-minus-sign');
});
});
function functiontwo() {
var tnum = <?php echo json_encode($_tempp1); ?>;
var tsign = <?php echo json_encode($_temppp1); ?>;
var signatoryidglobal = <?php echo json_encode($_SESSION['signatoryid']); ?>
}
</script>
this is the page looks like without json encode
this is the page looks like with json encode
The PHP function json_encode() returns a string (a JSON representation) and not an actual JavaScript object. You have to parse it in order to make use of the data passed through JSON.
var tnum = JSON.parse('<?php echo json_encode($_tempp1); ?>');
var tsign = JSON.parse('<?php echo json_encode($_temppp1); ?>');
var signatoryidglobal = JSON.parse('<?php echo json_encode($_SESSION['signatoryid']); ?>');
You can now access properties using dot notation or brackets.

Uncaught ReferenceError: testString is not defined

This is really weird..
I need to send a couple of variables through to jquery from PHP.. one is an INT and the other a string.
When $a is an INT it works fine but when i use a string, i get this error.. Uncaught ReferenceError: testString is not defined
Here is my code.
<?php $a = 'testString'; ?>
<script type="text/javascript">
var a = <?php echo $a; ?>;
alert(a);
</script>
I assumed that i needed to stick a (int) or (string) before the variable, but i wasn't entirely sure how to and unsuccessful in my googles/attempts.
Any ideas?
You forgot the quotes to make the value of var a a string:
var a = "<?php echo $a; ?>";
What you're writing into the document is:
var a = testString;
so javascript is looking for a variable called testString. Instead, you want the result to be:
var a = "testString";
so make sure you include the quotes around what php is writing in.
There are quotes missing in javascript code:
<script type="text/javascript">
var a = '<?php echo $a; ?>';
alert(a);
</script>

passing value to javascript to php variable: It do not work?

In this program similar_text function do not work but echo successfully print $var_1 and $var_2. What is the exact error?
<script>
var j=prompt('1st name','Name')
var l=prompt('2nd name','Name')
</script>
<?php
$var_1 = '<script>document.write(j)</script>';
$var_2 = '<script>document.write(l)</script>';
similar_text($var_1, $var_2, $percent);
echo $var_1, $var_2;
echo $percent;
?>
PHP is executed first, on the server, then it gets served and then only javascript is executed on the client-side. so the variables you are using in php part are not set at that moment.
If you need to interact with a php script from javascript, you odd to use an ajax request.
you need close php and open again
<script>
var j=prompt('1st name','Name')
var l=prompt('2nd name','Name')
</script>
<?php
$var_1 = '<script>document.write(?>j<?php)</script>';
$var_2 = '<script>document.write(?>l<?php)</script>';
similar_text($var_1, $var_2, $percent);
echo $var_1, $var_2;
echo $percent;
?>
or same.

Categories