Setting JS variable to PHP variable error - javascript

I want to use a php login name in my javascript game...
I have this at the top of my php page that runs the javascript:
<?php
$username = (isset($_GET['username']) ? ($_GET['username']) : "dude");
?>
In my javascript I have this... which doesn't alert the name at all and throws a Uncaught ReferenceError: daniel is not defined error:
var name = <?php echo $username; ?>;
alert(name);
And then I have this... which displays the name correctly at the top of the HTML:
<?php
echo "Welcome back " . $username . "...";
?>
If the name is being displayed correctly server side when the page has loaded, why can't it be alerted out from the Javascript?
Thanks

You aren't delimiting the value as a JavaScript string. It may be a string on the server, but not on the client. Do the following:
Change this:
var name = <?php echo $username; ?>;
To this:
var name = "<?php echo $username; ?>";

Enclose your php code within quotes.Try like this :
<script type="text/javascript">
var name = '<?php echo $username; ?>';
alert(name);
</script>

Related

how to pass php variable to javascript?

I am using following code to pass PHP variables to javascript. but it is not working.
function gto(str) {
document.getElementById('goto').action = str;
document.getElementById('ID').value = <?php echo "$userid" ?>;
document.getElementById('name').value = <?php echo "$user_name" ?>;
document.getElementById('gname').value = <?php echo "$usergname" ?>;
document.getElementById('fmname').value = <?php echo "$userfname" ?>;
document.getElementById('img').value = <?php echo "$userimg" ?>;
document.getElementById('email').value = <?php echo "$useremail" ?>;
document.getElementById('goto').submit();
}
Following is the PHP code
<?php
if($_POST["name"] == null)
{
$user_name = 'Annomyous';
}
else{
$user_name = $_POST["name"];
$userid= $_POST["id"];
$usergname= $_POST["gname"];
$userfname= $_POST["fname"];
$userimg= $_POST["img"];
$useremail= $_POST["email"];
}
echo "<p style='color : white'>$user_name";
echo "$userid" ;
echo "$gname";
echo "$fname";
echo "$img";
echo "$email";
echo "$user_name";
echo "$user_name</p>";
$user_name =htmlspecialchars($user_name);
$user_name =str_replace("<script>","", $user_name);
?>
the output is a follows:
ReAlItY TuTs104598758504708047866ReAlItY TuTsReAlItY TuTs//this is php echo output.
JAVASCRIPT OUTPUT:-
function gto(str) {
document .getElementById('goto').action = str;
document.getElementById('ID').value = ;
document.getElementById('name').value = Annomyous;
document.getElementById('gname').value = ;
document.getElementById('fmname').value = ;
document.getElementById('img').value = ;
document.getElementById('email').value = ;
document.getElementById('goto').submit();
}
Function gto is called here:
<button class="w3-btn header-btn" onclick="gto('Contact.php');">Contact Us</button>
I can see in PHP output I am getting all variable output.
but nin juavascript im getting only Annonymous why????
I need to pass post variables to contact us so i am using the form tag and javascript but this is not working Please help me!
Thanks in Advance
values from php to js can be passed in many ways, here's one of them
try to pass the php values when calling the js function, like this:-
<button onclick="gto('Contact.php','<?php echo $userid;?>','<?php echo $username;?>');">Contact Us</button>
and then get values on js function like this:-
function gto(str,userid,username) {
document .getElementById('goto').action = str;
document.getElementById('ID').value = userid;
document.getElementById('name').value =username;
}
that's it, now use the values in js as your wish
Uh, found another issue. The js is in smart quotes, which won't work... "`" is invalid. use "'".
Also, w3schools can't handle php in their editor, so it's no use.
Example for POST requests: https://www.w3schools.com/code/tryit.asp?filename=FQSA8MJYGJ47
Hope this helps.

Pass PHP Variable To JavaScript And Use Alert To Display

I am attempting the below to pass the value in my php variable to JavaScript, but I never have the alert display on screen. What is the proper way to do such?
PHP
<?php $date = '20170101'; ?>
JavaScript
var datestring = <? php echo $date; ?>;
var year = datestring.substring(0,4);
alert(year);
Fiddle:
https://jsfiddle.net/3ed6opj3/
The desired result that I want to display in the alert is 2017 - the answers below to this point have all been showing <? p
You have to add " on between the php script
var datestring = "<?php echo $date; ?>";
You need to add quotes
<?php echo "\"".$date."\""; ?>;

Failing to embed php in javascript

Im trying to give a javascript variable a value from php, this way:
<script type="text/javascript">
var id = <?php echo json_encode( $_GET['id']); ?>;
window.alert('Javascript still works');
The probem is once include the line: var id = <?php echo json_encode( $_GET['id']); ?>;
My javascript breaks any ideas on the way around this?

PHP variable in javascript "Invalid or unexpected token"

I'm having a problem trying to use a PHP variable within JavaScript. I keep getting the following message.
"Invalid or unexpected token. Message: Undefined variable: example."
I'm unsure why example is being undefined, as it is defined within the php code. Here is my code:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = "<?php echo json_encode($example); ?>";
</script>
Does anyone have any suggestions? I have also tried the following javascript that results in the same problem:
<script type="text/javascript">
var php_var = "<?php echo $example; ?>";
</script>
Firstly, your original code has a syntax error: $example = '2' needs a semicolon.
Secondly, the next piece of code is just assigning the string <?php echo $example; ?> to the JavaScript variable php_var where the $example PHP variable is first substituted. The $example variable should be initiated properly first, however, for this to work.
As a separate note: JS cannot execute PHP directly -- only a PHP server can do so. What you're most likely trying to do is this:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = '<?php echo $example ;?>';
</script>
This should work, use single quotes
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = '<?php echo $example; ?>';
</script>
Tried and working both variant:
<?php
$example = '2';
?>
<script type="text/javascript">
var php_var = <?php echo json_encode($example); ?>;
console.log(php_var);
</script>
<script type="text/javascript">
var php_va = "<?php echo $example; ?>";
console.log(php_va);
</script>

Ajax function on button press

I am trying to get information to post via PHP on button click, everything in my code looks right, and when I view the page source everything is filled in the way it should be. When I pull up the debugger when the button is clicked it does not make any calls at all, here is my button
<button type="button">Continue</button>
here is my ajax call
$(document).ready(function() {
$("button").click(function(){
var Id = <?php echo $give ?>;
var Ids = <?php echo $rec ?>;
var ex = <?php echo $exchange ?>;
var ret = <?php echo $tost ?>;
var email = <?php echo $email ?>;
var name = <?php echo $name ?>;
var pe = <?php echo $pe ?>;
var re = <?php echo $re ?>;
$.post("postts.php", {
Id: Id,
Ids: Ids,
ex: ex,
ret: ret,
email: email,
name: name,
pe: pe,
re: re
}, function(data){
alert(data);
$("p").text(data);
}, 'json' );
});
});
all of my vars will populate with the correct information, I just don't know why when I click the button it does nothing. I am not sure if I have made a typo, or if my syntax is wrong, this is only the second time I have done something like this.
You have error in writing variable values from PHP to JavaScript, you must wrap PHP output by quotation marks, so JavaScipt will "see" string ;)
instead of:
var email = <?php echo $email ?>;
write:
var mail = '<?php echo $email ?>';

Categories

Resources