transfer a Variable from php to js - php

I got really confused when i tried to transfer variables from php to js.
everything is fine when i try to get value using an id
for example:
var name = $("#name").val();
but my question is, if i want to convert for example this variable:
$id = 182938; //the id of the user
to this variable:
var id;
this question might be dumb... maybe easy for you, but not for me :p
I have looked it up and only found something like this anywhere i looked for:
<?php
$number = rand();
?>
<script language="javascript">
var num = <?php echo $number ?>
</script>
Does it have the same affect as passing down the value?
Thanks!!

Not quite. Encoding as JSON will ensure that it is a valid JavaScript literal.
var num = <?php echo json_encode($number) ?>

what the code does is:
<?php
$number = rand(); //assign random number to $number. let's say it's "3"
?>
//then these are printed on the page normally
<script language="javascript">
var num = <?php echo $number ?> //the $number is echoed at this position
</script>
and then the browser receives:
<script language="javascript">
var num = 3;
</script>

You have to generate syntactically VALID javascript. PHP can echo text into ANY part of the page it's generating, but that doesn't necessarily mean it's actually USABLE text. In your case, you've forgotten a ;, so your generated javascript is actually a syntax error:
var num = <?php echo $number ?>;
^--- missing
The same sort of thing occurs when you're outputting text. Consider where you're storing someone's name into a variable:
<?php
$name = "Miles O'Brien"; // <-- note the single quote
?>
<script>
var name = <? php echo $name ?>;
</script>
This LOOKS ok, but it'll actually generate yet another syntax error:
var name = Miles O'Brien;
there's no quotes around the whole string, and the embedded quote will START a string in javascript, leading the JS interpreter to complain about an undefined variable "Miles", an undfined variable "O", and an unterminated string literal.
Instead, the PHP should have been:
var name = <? echo json_encode($name) ?>;
The JSON encapsulation guarantees that you're embedding syntactically valid Javascript values.

Related

I want to use session variable value in javascript

Here I want to use session variable's value in javascript function. I tried
var varname = '<?php echo $_SESSION["variable_name"]; ?>';
But it doesn't pass the value it shows the string
so how can i use session variable of php inside the javascript.
Actually I want to check captcha code in java script side.
Here i already make contactus.php file where I generat captcha value from rand function. Then i store this value in session variable. Here I already made validation.js file to validate contact us form fields so in same file i want to validate captha so for that I has been trying below code but its not working .
var cap = document.frm.captcha.value;
var ca = '<?= addslashes($_SESSION["code"]); ?>';
alert (cap); //ITs shows my entered value perfectly
alert (ca); //but it doesn't show generated captcha value. it simply print '<?= addslashes($_SESSION["code"]); ?>'//
if(cap!=ca)
{
alert("Insert correct captcha code");
document.frm.captcha.focus();
return false;
}
I checked session variable value it works fine on php page but dosen;t work on javascript page.
<script type="text/javascript">
<?php echo "var variable = '". $_SESSION['variable']."';" ?>;
</script>
The file which contains this code must be named .php and has to be a session_start(); at the beginning of the PHP-File.
Then this code should work.
There is several posibilities, why your code isn`t working.
There is an error in variable (Eg unescaped quote)
Code is outside of Javascript code.
Session is not started in the moment of getting variable
For fixing this 3 errors you need to use following code -
<?php session_start(); ?>
<script type="text/javascript">
var varname = '<?= addslashes($_SESSION['variable_name']); ?>';
</script>
If in your session variable is not a string or number you need to pack it to the JSON object. In this case you can just make following:
<?php session_start(); ?>
<script type="text/javascript">
var varname = <?= json_encode($_SESSION['variable_name']); ?>;
</script>
Last variant of code will make all types of variable are frendly to JS. Also string.
For example with json_encode from asd'd"sa string you will get "asd'd\"sa" string.
UPD:
If you use this file like JS file like follows:
<script type="text/javascript" src=".../path/to/file.php"></script>
for correct work you need to use following code.
<?php
session_start();
header('Content-Type: text/javascript');
?>
var varname = '<?= addslashes($_SESSION['variable_name']); ?>';
Try like this:
<script type="text/javascript">
var varname = <?php echo $_SESSION["variable_name"]; ?>;
</script>

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';

firefox complaining about valid json... invisible invalid character?

I'm writing a php script that needs to load a 2D array into a js variable as json. First i make the array then use json_encode to turn it into a string. Then I run a small bit of js to get it accessable on the client side. Like so:
$sBaseData = Filters::$sFilterBaseTypeData;
$sBaseData = str_replace('\r',' ',$sBaseData);
$sBaseData = str_replace('\n',' ',$sBaseData);
$sBaseData = str_replace('\t',' ',$sBaseData);
echo <<<HTML
<script type="text/javascript">
var validation_data = JSON.parse('$sBaseData');
</script>
HTML;
Firefox complains about an unexpected character here:
var validation_data = JSON.parse('{"enumeration":{"js":"","msg":""},"date":{"js":" var parts = widget.value.split('-'); var d = new Date(parts[0],parts[1],parts[2]); PASS = (d.getDay()>=1); ","msg":"Invalid date. Please Enter a date in the format: YYYY-MM-DD"},"text":{"js":"","msg":"what did you do?"},"integer":{"js":"if (isNaN(widget.value)) { PASS = false; } else { intVal = parseInt(widget.value); PASS = (widget.value == intVal); } ","msg":"Please enter an integer value"},"decimal":{"js":"PASS = isNaN(widget.value); ","msg":"Please enter a number"},"group":{"js":"","msg":""},"dealer":{"js":"","msg":""}}')
I tried using http://jsonlint.com/ to find out which character was at fault but it says it's all valid and wonderful. I replaced some characters that were causing issues, is there anything else I should be replacing?
The problem is you have ' in your string while you are using ' to quote the string.
If your json string is valid, you don't need to parse it even. The below will work.
echo <<<HTML
<script type="text/javascript">
var validation_data = {$sBaseData};
</script>
HTML;
Uh...
var parts = widget.value.split('-');
Putting that in a string that uses single quotes will break it. Use a JSON encoder to output your JavaScript literal.
Your JSON is valid but in your js code the simple quote closes the parse function's argument.
Try like this:
"date":{"js":" var parts = widget.value.split(\'-\');

Passing parameters to Javascript using PHP

I have the following line of code:
My Tweets!
Now while this is working perfectly fine the following line is not:
My Tweets!
Can anyone help me out why it is not working and suggest any changes? The variable I want to pass to the Javascript function is a PHP variable. I have tried the PHP with single quotes and double quotes but it is not working.
You need quotes for both the php side and the Javascript side. You've only got php quotes there.
My Tweets!
looks weird but it should work, though I'm no php expert. Note that if there's any chance that "myid" (on the php side) might contain user-supplied data (like, something that came from an <input> field at some time), or if it's otherwise unpredictable, then it has to be put through something on the server side to make sure that the resulting tag is "clean".
I usually do as following:
<script>
var jsvar = <?=json_encode($php_var)?>;
</script>
After that I can use jsvar under the javascript codes. And for readability I usually place all those assignments in an own script tag.
What you gain by using <?=json_encode($php_var)?> is that you won't need to go on escaping, and it works for arrays and hashes as well as strings, numbers etc...
For example, following php code:
<?php
$php_string = "hello";
$php_array = array( 'a', 'b', 'c' );
$php_hash = array( 'a' => 1, 'b' => 16, 'c' => 42 );
$php_number = 123;
$php_bool = false;
$php_null = null;
?>
<script type="text/javascript">
var js_string = <?=json_encode($php_string)?>;
var js_array = <?=json_encode($php_array)?>;
var js_hash = <?=json_encode($php_hash)?>;
var js_number = <?=json_encode($php_number)?>;
var js_bool = <?=json_encode($php_bool)?>;
var js_null = <?=json_encode($php_null)?>;
</script>
produces the following result:
<script type="text/javascript">
var js_string = "hello";
var js_array = ["a","b","c"];
var js_hash = {"a":1,"b":16,"c":42};
var js_number = 123;
var js_bool = false;
var js_null = null;
</script>
You forgot to Quote your answer. You are echoing the string OK, but you need to ' ' the response so JavaScript will know it's a string. You can use ' or \"
My Tweets!
Uses short echo thing.

How do I use PHP variables as values for the <script> tag when rendering jQuery code in my CakePHP view?

I m new to CakePhp and JQuery.
I am getting an error in using the cakephp code inside my JQuery.
My code
<script type="text/javascript">
$(document).ready(function(){
var attributeid;var fieldname;
$("#"+<?=$r['Attribute']['id'];?>).change(function () {
fieldname=<?=$r['Attribute']['label'];?>;
alert(fieldname);//this show me that undefined
attributeid=<?=$r['Attribute']['id'];?>;
alert(attributeid);//But this works
});//attribute change
});//ready function
if I echoed ($r['Attribute']['label'];) this value is coming inside my <?php ?>.
But not inside my JQuery.
Note :
attributeid=<?=$r['Attribute']['id'];?>;
alert(attributeid);//But this works
Error:
Name is not defined
fieldname=name;
alert(fieldname);
You are not thinking about how this is translating over once the variables are echoed.
If you have a variable $x with the contents "test", doing this:
var x = <?=$myvar?>;
Will result in:
var x = test;
This is not valid (unless test is a variable) because you need quotations around it to make it a string:
var x = "<?=$myvar?>";
Which then results in the valid:
var x = "test";
The reason it works with the other variable is because you are echoing an ID, which is an integer:
var x = <?=$myid?>;
Would translate to:
var x = 5;
Which is perfectly valid.
All this being said, you should put all the stuff you want to send over to Javascript in an array and call json_encode on it to easily and safely print the values over. Without it, you have to worry above about escaping quotes in the string and such.

Categories