How to assign Php variable value to Javascript variable? [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What's the best way to pass a PHP variable to Javascript?
I am using the following code:
<script type="text/javascript">
<?php $ctnme = $_SERVER['REQUEST_URI'];
$cnme = explode("/",$ctnme);
echo $cname = $cnme[1];
?>
var spge = <?php echo $cname; ?> ;
alert(spge);
</script>
The value doesn't alert. What is the mistake?

Essentially:
<?php
//somewhere set a value
$var = "a value";
?>
<script>
// then echo it into the js/html stream
// and assign to a js variable
spge = '<?php echo $var ;?>';
// then
alert(spge);
</script>

The most secure way (in terms of special character and data type handling) is using json_encode():
var spge = <?php echo json_encode($cname); ?>;

Use json_encode() if possible (PHP 5.2+).
See this one (maybe duplicate?): Pass a PHP string to a JavaScript variable (and escape newlines)

Put quotes around the <?php echo $cname; ?> to make sure Javascript accepts it as a string, also consider escaping.

**var spge = '';**
alert(spge);

Related

Pass PHP variable with GET to another PHP page [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
There's probably something pretty easy here that I'm missing but I can't seem to figure it out.
I'm trying to pass a PHP variable "$session" from one PHP page to another PHP page using GET. The GET shows in the new URL but the value is not passed to the page so that I can retrieve it. Below is the relevant code.
On the main Index.php page.
<div class="mapgroup">
<table>
<tr>
<td></td>
<td id="refreshKML" ></td>
<?php echo "<td><a href='3D-Earth.php?session=$session' title='Full Size Google Earth' target='_blank' >Click here</a> for full size Google Earth</td>"; ?>
</tr>
</table>
<div id="map3d"></div>
</div>
The "$session" variable is passed to 3D-Earth.php using GET and the correct value shows in the URL. However, when I try to retrieve the variable with:
<?php
$session = $_GET["session"];
?>
and then try to create a javascript variable:
<script>
var session = <?php echo $session; ?>;
</script>
that I will use to concatenate the below string:
var href = 'http://localhost/satellites/' + session + '/master.kml';
nothing is being passed.
I appreciate any help anyone can provide. Thanks in advance.
Additionally, I've inserted the below code at the bottom of my 3D-Earth.php page to verify that the GET is being passed.
<div>
<table><p style='color:white;' >Hello " <?php echo $session; ?> " world!</p></table>
</div>
The result is an empty string that shows: Hello " " World! Anyone know what I might be doing wrong?
Try like this:
var session = '<?php echo $session; ?>';
I suggest stop using names like 'session' that might conflict with php reserved words. Maybe that's not the issue here, but avoids many other problems and confusions.
Also in javascript put the echo in quotes:
var session = '<?php echo $session; ?>';
You should put a single quotes around your variable like this
var session = '<?php echo $session; ?>';
As above answers say, you have to have single quotes around a php statement when you want to use it in javascript. So var session = 'php statement'; is the right way to go.
have you tried to put this code
<script>
var session = <?php echo $session; ?>;
</script>
under this code ??
<?php
$session = $_GET["session"];
?>

javascript not reading characters

I'm sure the answer to this is stunningly simple - but I can't find it!
I have a javascript embedded in a PHP (which will return a string value to my android app) and for some reason it will only read the PHP echo'd variable when it contains all integers!
I need it to read characters and integers since usernames consist of that.
Looking forward to tips - embarassed I couldn't figure this one out on my own;
Notes on my code: I deactivated the Android function at the end, since the problem occurs before that gets implemented; also set up $myvar = '20' so you can see it works for all integers;
<?php
if (!isset($_SERVER['WEBAUTH_USER'])){
$login = 'Wrong username';
}else{
$login = $_SERVER['WEBAUTH_USER'];
//$myvar = 'Hello, world';
}
$myvar = $login;
//$myvar = '20';
//echo $myvar;
?>
<script type = "text/javascript">
jsvar = <?php echo $myvar;?>;
document.write(jsvar);
//Android.getValue(jsvar);
</script>
You're leaving out quotes:
jsvar = "<?php echo $myvar; ?>";
Of course, there'll be problems if the string contains quotes, so a better solution is to use something like a JSON utility to sanitize the string.
It worked with numeric strings because JavaScript understood those as numeric constants.

show hide div based on mysql table row value

hi guys im trying to show and hide div according to mysql value but i couldnt do it can you help me what im doing wrong
here is my code thanks a lot for your ideas
var Value = <?php echo json_encode($valuek) ?>;
if (Value==1){
$('#show_hide').show();
}
else{
$('#show_hide').hide();
}
<?php
$valuek = $session->userinfo['vcc'];
?>
<div id="show_hide">
some code
</div>
<?php echo json_encode($valuek) ?>
will return a json string, instead try just using "echo"
<?php echo $valuek ?>
If all you are going for is a boolean value then there is simply no need for JSON.
Echo the value directly into the JavaScript. Remember to ensure you are passing a valid boolean value.
PHP code -
<?php
$showDiv = ($dbValue == 1? 'true' : 'false');
?>
JavaScript + PHP injection -
<script>
var value = '<?php echo $showDiv; ?>';
<script>
Don't forget to wrap the PHP injected value with quotes.
$valuek = $session->userinfo['vcc'];
I'm not sure if you have the code in this order in your php file, or just showed pieces of code in this order, but Should go BEFORE your js code. It has no value when js code is run.
To see what $valuek is, just echo it on top of the screen
<?php echo "<h1>$valuek</h1>" ?>.
Or just look at the source - at your js function, to see what is printed after 'var Value ='
That's the main thing really - to make sure that you getting what you expect from session.
And as been said, you don't need jason_encode, but you do need a semi-colon after echo command.
Also, I hope your jquery code is within $(document).ready function, not as is.

PHP variable not passing correctly to 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.
I am trying to validate input login via javascript by passing PHP variables. I cannot execute it properly for some reason. I'd appreciate your comments. Here's the code:
PHP:
$personal = mysqli_query($connect,"SELECT * FROM basic ORDER BY user_id DESC ");
while($row = mysqli_fetch_array($personal)){
$user = $row['username'];
$user_password = $row['password'];
}
Javascript / jQuery:
function enter_log() {
var login_username = $("#username_field_log");
var pass_password = $("#pass_field_log");
var button = $("#enter_field_log");
var php = "<?= echo $user; ?>";
if ((login_username.val() == "") || (pass_password.val() == "")) {
$("#user_log_info").fadeIn('slow');
$("#user_log_info").text("Not a proper login input");
login_username.addClass("error");
pass_password.addClass("error");
return false;
}
else if ((login_username.val() != php ) || (pass_password.val() == "")) {
$("#user_log_info").fadeIn('slow');
$("#user_log_info").text("Not a proper login input");
login_username.addClass("error");
pass_password.addClass("error");
return false;
}
}
So in other words - the code should return false ( and it does so ) when the fields are empty but it doesn't return TRUE when the input is correct ( I mean when the username is correct ) so I assume the PHP variable $user is not passed by correctly to javascript?
Validation should not be done via Javascript. For any number of reasons I can crack open Firebug or Chrome and hack your web page if you validate there. You should use PHP code for your validation and make sure you properly sanitize your input.
Regarding your use of PHP tags:
var php = "<?php echo $user; ?>";
Is how you should write your code. Per the PHP Manual
http://www.php.net/manual/en/language.basic-syntax.phpmode.php
1. <?php echo 'if you want to serve XHTML or XML documents, do it like this'; ?>
2. <script language="php">
echo 'some editors (like FrontPage) don\'t
like processing instructions';
</script>
3. <? echo 'this is the simplest, an SGML processing instruction'; ?>
<?= expression ?> This is a shortcut for "<? echo expression ?>"
4. <% echo 'You may optionally use ASP-style tags'; %>
<%= $variable; # This is a shortcut for "<% echo . . ." %>
Item 1 is actually the preferred format.
Short tags (example three) are only available when they are enabled via the short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option.
It should be var php = "<? echo $user; ?>";
or
var php = "<?= $user; ?>";
echo and <?= is not needed
I am in agreement that you should not be validating things like this.
Use JS to validate the form on submit to ensure its completed and all sections are complete, then use php or any scripting language then to do a server side validation.
If you want it so that if it fails then the JS displays a message then rather than passing the user details etc then pass a simple php boolean to a variable
for instance
var userValid =
The php $valResult will be the result given by the db check etc
then use this js variable.
A simple, reliable PHP to Javascript encoder is json_encode.
var jsVal = <?php echo json_encode($phpVal); ?>; // note trailing semicolon!

Reading a PHP file variables from external JS

How may I retrieve, by JS (and I mean an external script), the value of some variables assigned in a php include file like the one below?
<?php
$var1 = "a";
$var2 = "foo";
?>
Assuming that you mean using an AJAX request to retrieve the variables...the best way to do that would be:
<?php
$array["var1"]="a";
$array["var2"]="foo";
echo json_encode($array);
?>
And on the JS end, you would want to do:
json = eval( "(" + response + ")" );
And var1 and var2 would be json.var1/json.var2
Edit:
In that case you should be able to do something like:
<script type="text/javascript">
var phpvars = <?php echo json_encode($array); ?>;
<script>
And just place that above where whistle.js will be included, and then the Javascript in that file will be able to access the variables through phpvars. (Changing the variables.php file so that it has the same format as above, except no echoing of it).
To reiterate the previous feedback, PHP is used to generate HTML -- The PHP file itself is never available to the browser. You can use the variables.php to generate hidden tags, then JavaScript to read them.
eg,
variables.php output:
<div id='varA' style='display:none'>foo</div>
javascript:
document.getElementById('varA').innerText
or
variables.php output:
<input id='varB' type='hidden' value='bar' />
javascript:
document.getElementById('varB').value

Categories