Uncaught ReferenceError: not defined - javascript

I'm attempting to make a comments system, and their comment gets posted in a div on submit. I need to set their username:
var session_username = <?php echo $_SESSION['username']; ?>;
var full = '<div> ...' + session_username + '...</div>';
$('#commentslice').prepend(full);
In the console it's saying:
Uncaught ReferenceError: [whatever the username is] is not defined.

Unless your PHP value (presumably a string) contains its own quotes, you should wrap it:
var session_username = "<?php echo $_SESSION['username']; ?>";
Let's say the username is "foo" and you haven't wrapped it. The replacement will come out to:
var session_username = foo;
which is a reference to the variable foo. If that's not defined (and usernames will likely be randomish strings that aren't in your code), you'll run into this error.
This won't change how the PHP behaves at all, it will still replace that snippet with the value of the session username. The JS, however, will see a string variable and treat it as a bit of text.

var session_username = "<?php echo $_SESSION['username']; ?>";
or
var session_username = <?php echo json_encode($_SESSION['username']); ?>;

Related

Javascript check if PHP variable is defined or not

I can not find an answer to my problem and I am also not sure if this is possible or not.
Is there any way to check if a PHP variable is defined or not with javascript?
This is an example:
var op = <?PHP echo json_encode($op); ?>;
if $op is not defined I got an error in javascript:
Events:362 Uncaught SyntaxError: Unexpected token )
I understand this is normal because this variable does not exist in PHP. But there is a way to avoid the error if the variable does not exist?
Change:
var op = <?PHP echo json_encode($op); ?>;
To:
var op = <?PHP echo (!empty($op) ? json_encode($op) : '""'); ?>;
PHP is executed on the server, before the response is even sent to the user. Javascript is executed on the browser, once the user receives the response. So "communicating" in the way you describe is not possible. Just test in PHP if $op is empty, and output accordingly.
You can check it:
var op = <?php echo (isset($op) && $op) ? json_encode($op) : 'null'; ?>;
empty() is your best choice. http://php.net/manual/en/function.empty.php
var op = <?= !empty($op) ? json_encode($op) : '""' ?>;
Try like this :
var op = <?= isset($op) ? json_encode($op) : "" ?>;

Referencing a defined html variable in JS

My index.php page includes a config.php file, which returns an array that I have defined some variables in by using "define('var1' , 10)".
I am trying to validate my forms input, but I can't figure out how I can reference var1 from within the JS function. What is the easiest way to do this?
Just echo it to a javascript variable:
<script type="text/javascript">
var var1JS = "<?php echo $var1; ?>";
</script>
Not quite sure I am full understanding without seeing the code but, you could echo the variable from the PHP array in the JS function (as above answer).
Or Echo the entire JS query:
$y = count($PHPdata_array);
echo "function exampleFunction() {";
echo "var ArrayName = [";
for ($i = 1; $i <= $y; $i+=2) {
echo "{" . $PHPdata_array[$i] . "," . $PHPdata_array[$i-1] . "},";
}
echo "];";

Can I get a value localized by javascript in blade template?

In html, I can get a value localized by below code:
{{Lang::get('frontend/error_message.EMAIL_BLANK')}}
I want to use javascript to check valid input data, and get value from localized, but it not working with below code:
error = <?php echo \Lang::get('frontend/error_message.EMAIL_BLANK');?>
error = <?php echo Lang::get('frontend/error_message.EMAIL_BLANK');?>
error = {{Lang::get('frontend/error_message.EMAIL_BLANK')}}
You probably just need to put in some "
error = "<?php echo \Lang::get('frontend/error_message.EMAIL_BLANK');?>"
error = "<?php echo Lang::get('frontend/error_message.EMAIL_BLANK');?>"
error = "{{Lang::get('frontend/error_message.EMAIL_BLANK')}}"

Passing PHP array to javascript using json_encode giving errors?

I fetch some information from DB - shown here:
$link = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$handle = $link->prepare("SELECT dropAddress FROM mv_bookingEst WHERE userID='$userID'");
$handle->execute();
$result = $handle->fetchAll(\PDO::FETCH_OBJ);
//print_r($result);
$x = 0;
foreach($result as $obj){
$resultArray[$x] = $obj->dropAddress;
$x++;
}
and then in my javscript:
var count = "<?php echo json_encode($resultArray); ?>";
However I get the following error:
Syntax error: unexpected number -->
var count = "["-33.8935642, 151.20227810000006","-33.857653, 151.20853699999998 ...
If I replace json_encode($resultArray) with echo ($resultArray[0]) the values pass fine. Not sure how to fix it because everything I've read uses this method. TIA
var count = "<?php echo json_encode($resultArray); ?>";
You are returning the result of the json_encode inside of a JavaScript string. Your syntax error shows this:
Syntax error: unexpected number --> var count = "["-33.8935642, 151.20227810000006","-33.857653, 151.20853699999998 ...
Unless there's a failure in coversion, json_encode returns valid JavaScript syntax, so you should just use it as-is without any adornments in your javascript:
var count = <?php echo json_encode($resultArray); ?>;
If you want to take into consideration the possibility of failure, then you can use this instead:
var count = <?php
$tmp = json_encode($resultArray);
echo ($tmp === false ? 'null' : $tmp);
?>;

Setting JS variable to PHP variable error

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>

Categories

Resources