boolean variable values in PHP to javascript implementation [duplicate] - php

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I've run into an odd issue in a PHP script that I'm writing-- I'm sure there's an easy answer but I'm not seeing it.
I'm pulling some vars from a DB using PHP, then passing those values into a Javascript that is getting built dynamically in PHP. Something like this:
$myvar = (bool) $db_return->myvar;
$js = "<script type=text/javascript>
var myvar = " . $myvar . ";
var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
</script>";
The problem is that if the boolean value in the DB for "myvar" is false, then the instance of myvar in the $js is null, not false, and this is breaking the script.
Is there a way to properly pass the value false into the myvar variable?
Thanks!

use json_encode(). It'll convert from native PHP types to native Javascript types:
var myvar = <?php echo json_encode($my_var); ?>;
and will also take care of any escaping necessary to turn that into valid javascript.

This is the simplest solution:
Just use var_export($myvar) instead of $myvar in $js;
$js = "<script type=text/javascript>
var myvar = " . var_export($myvar) . ";
var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
</script>";
Note: var_export() is compatible with PHP 4.2.0+

$js = "<script type=text/javascript>
var myvar = " . ($myvar ? 'true' : 'false') . ";
var myurl = 'http://someserver.com/ajaxpage.php?urlvar=myvar';
</script>";

Related

Javascript php variable not passing with http_build_query [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
Why does this not work?
var data1 = "<? http_build_query($_GET); ?>";
var data2 = "buy.php?";
var url = data2+data1
document.getElementById('framebox').src = url;
Thanks.
Because data1 is empty (PHP is not outputing anything), try:
var data1 = "<?= http_build_query($_GET); ?>"; // or
var data1 = "<?php echo http_build_query($_GET); ?>";
Any reason you're using PHP to build the query string instead of doing it directly in Javascript?
You can also archive it the plain old pure javascript way:
var data1 = location.href.split('?').pop();
var data2 = "buy.php?";
var url = data2+data1
document.getElementById('framebox').src = url;
But it's much more fun to mix stuff.....

Printing PHP variables into JavaScript variables [duplicate]

This question already has answers here:
Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]
(14 answers)
Closed 9 years ago.
Yes I know this question gets asked a lot, but I'm fairly new to JS and I need to use a php variable in some JS. I'm more then aware that PHP is executed server side and JS is client side however other people claim that this works.
I've got a PHP variable called "test1" that I want to log to the JS console (for instance):
<?php
$test1 = '1';
print '
<script type="text/javascript">
var carnr;
carnr = "<?php print($test1); ?>"
console.log(carnr);
</script>';
?>
What this does is print " " to the JS console. Not exactly what I was hoping for.
Now this may not even be doable and I may have to pass the variable off the page and back in again with AJAX, but I'd rather have a quick and easy solution if there is one available!
Any help is appreciated.
You could do this.
<script>
var JSvar = "<?= $phpVar ?>";
</script>
The PHP will be parsed and the value of $phpVar will become the value of JSvar whatever.
Make sure you encode phpVar properly. For example, if phpVar contains a double quote, you'll end up with a broken JS
Use this no need to give "" => change to '.$test1.'..
<?php
$test1 = '1';
print '
<script type="text/javascript">
var carnr;
carnr = "'.$test1.'"
console.log(carnr);
</script>';
?>
try
<?php $test1 = '1'; ?>
<script type="text/javascript">
var carnr;
carnr = "<?php print($test1); ?>"
console.log(carnr);
</script>
Generally, it is better to not print static stuff with php, but to have static (that is unchanging) stuff directly in HTML and only use PHP on the parts that really need it.
You made a mistake do it so:
<?php
$test1 = '1';
echo '<script type="text/javascript"> var carnr; carnr = "'.$test1.'" console.log(carnr)</script>';
?>
Since you're writing your JS with your PHP, you can simply do:
$test1 = "blah";
echo "<script type=\"text/javascript\">console.log($test1);</script>";
You are already in open php tag. When printing the line just append the variable to the output by using a dot.
Example:
print 'variable1 '.$variable1.' is now printed';

Passing a php array into javascript using JSON

I have a multidimensional array, here:
$noticeDate = json_encode( $noticesDates );
and I want to pass the array into javascript:
var unavailableDates[] = $noticeDate;
Both variables are in the same php file so there is little point using $.getJSON, which basically looks for the variable in an external file. However, how do I pass the object into the javascript array in the same script.
Cheers
You cant directly assign php variables to js, but you can use something like that:
<script>
var unavailableDates = jQuery.parseJSON('<?php echo json_encode($noticeDates) ?>');
</script>
use this
var array = JSON.parse("<?php echo json_encode($noticesDates) ?>");
Try this one:
$.pareseJSON()
here is example:
var json = "<?php echo json_encode($noticesDates); ?>";
jsArray = jQuery.parseJSON(json);

how to pass array string in JavaScript function from PHP end as a argument?

I am getting the error missing ) after argument list in my Firebug console.
emissing ) after argument http://a8.sphotos.ak.fbcdn.net/hphotos-ak-snc7/s720x720/393131_320846714645076_100001592501599_911297_470580896_n.jpg
My question is how to pass $char_data variable in JavaScript function as a argument
Define php variable:
<?php
$chart_data = "['NBA',1],['NFL',2],['MLB',3],['NHL',4]";
$div = "graph";
?
Call JavaScript function with define argument
<script>
dynamicChartArray('<?php echo $div;?>','<?php echo $chartdata;?>')
</script>
A function of JavaScript
<script>
function dynamicChartArray(div,chartdata){
var myData = new Array(chartdata);
var myChart = new JSChart(div, 'pie');
alert(chartdata+div);
}
<script>
Rather than creating an array out of a string in javascript, why not just just get the PHP to output it as an array to start with?
Just add an extra set of [] which javascript reads as an array.
$chart_data = "[['NBA',1],['NFL',2],['MLB',3],['NHL',4]]";
then ditch the quotes on the output (which are responsible for causing the error messages)
dynamicChartArray('<?php echo $div;?>', <?php echo $chartdata;?>);
and then myData can just equal chart data (since its already an array)
var myData = chartdata;
'<?php echo $chartdata;?>'
This is going to echo '['NBA',1],['NFL',2],['MLB',3],['NHL',4]'. Note how there are single quotes inside the single quotes.
new Array(chartdata)
This will just make an array, with one element, the string "['NBA',1],['NFL',2],['MLB',3],['NHL',4]".
Try doing dynamicChartArray('<?php echo $div;?>',[<?php echo $chartdata;?>])
This will make chartdata an array of arrays.
Instead of
$chart_data = "['NBA',1],['NFL',2],['MLB',3],['NHL',4]";
Use
$chart_data = "[\"NBA\",1],[\"NFL\",2],[\"MLB\",3],[\"NHL\",4]";
Change your call to this:
dynamicChartArray('<?php echo $div;?>',[<?php echo $chartdata;?>])
And function to this:
function dynamicChartArray(div,chartdata){
var myData = chartdata;
var myChart = new JSChart(div, 'pie');
alert(chartdata+div);
}
change this:
dynamicChartArray('<?php echo $div;?>','<?php echo $chartdata;?>')
to this:
dynamicChartArray('<?php echo $div;?>', [<?php echo $chart_data;?>]);
and see if it works
You dont need var myData = new Array(chartdata);.
chartdata is already an array.
Take a look at json_encode.
$chart_data = json_encode(array(array('NBA',1),array('NFL',2)));
which will produce a json string ready to echo into your script
string(21) "[["NBA",1],["NFL",2]]"
You should have a look at the output. I bet it is:
dynamicChartArray('graph','['NBA',1],['NFL',2],['MLB',3],['NHL',4]')
and you can already see that you have problems with the quotes.
Instead of creating a string, I suggest to create an array and use json_encode:
$chart_data = array(
array('NBA',1),
array('NFL',2),
array('MLB',3),
array('NHL',4)
);
and
dynamicChartArray('<?php echo $div;?>', <?php echo json_encode($chartdata); ?>)
JSON happens to be valid JavaScript as well and it gives you more possibilities to process the data on the server side.

How to use a PHP variable in JavaScript? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
Possible Duplicate:
Passing PHP variable into JavaScript
I want to obtain a PHP variable, to use it in an if-condition in JavaScript.
I was trying to use it like this:
var phpLogin = <?php $_SESSION['login'] ?>;
But it's wrong in syntax terms. So, how can I use a PHP variable in JavaScript?
Use json_encode and don't forget echo.
var phpLogin = <?php echo json_encode($_SESSION['login']) ?>;
You forgot the echo.
<?php echo $_SESSION['login']; ?>
or just
<?=$_SESSION['login']?>
The problem in your code is that you forgot the echo:
var phpLogin = <?php echo $_SESSION['login'] ?>;
Try:
var phpLogin = "<?php =$_SESSION['login']; ?>";
It may look like overkill, but for safety reasons you should use json_encode when echo'ing directly to PHP:
var phpLogin = <?=json_encode($_SESSION['login'])?>;
Or, in its longer form:
var phpLogin = <?php echo json_encode($_SESSION['login']); ?>;
Or, to also accept empty sessions:
var phpLogin = <?php echo #json_encode($_SESSION['login']); ?>;
This will simply output NULL when there's no login session.

Categories