0

I have the following code that passes a variable (EmployeeID) from PHP into JavaScript:

EmployeeID= <?php echo "$EmployeeID"?>;

The issue is that the variable EmployeeID in PHP might not exist, in which case, after I run the JavaScript code, I receive an error

Uncaught SyntaxError: Unexpected token

When I look into the Source Code in Dev Tools I can see this:

EmployeeID = ;

What would be the best way to handle this error? I tried

if (EmployeeID == null){
    EmployeeID = "0"; //0 - stands for generic variable in case if EmployeeID doesn't exist
}

Any help would be greatly appreciated!

3 Answers 3

2

This php code outputs either $EmployeeID value or 0, so your js var holds 0 when $EmployeeID has falsy value:

var EmployeeID = <?php echo $EmployeeID ? $EmployeeID : 0 ?>;
Sign up to request clarification or add additional context in comments.

4 Comments

Works great! Thanks!
May be it is better to check isset($EmloyeeID) if variable might not exist
@VitalijsG. indeed it maybe. But I just showed an example how to always output something. Even ?? operator can be used, which eliminates the need for isset.
Yeah I would have gone with null coalesce. DRY and all that, and will avoid undefined variable notices in the log file in case it's not set.
1

As the first answer states, a shothanded if is a great solution for this case

<?php echo $EmployeeID ? $EmployeeID : 0 ?>

But in this case the output will be 0 if $EmployeeID == 0, null, false, '', for this case i strongly recomment you to use the method ´isset()´, as the variable may not be declared (for example if an employeeID is actually 0)

<?php 
  if(isset($EmployeeID)){
       // Do something here
  } else {
       // whatever u need
  }

For a better refference about php-isset

Comments

0

So the other answers will likely work fine for what I'm assuming is a numeric value, but in case you have a text value, you'll want to ensure it's properly escaped for JavaScript. json_encode() is perfect for this. I'd do something like this:

EmployeeID= <?= json_encode($EmployeeID ?? null) ?>;

This will ensure that any text is properly escaped, and the null coalesce operator gives you a default without triggering notices about undefined variables in case the variable doesn't have a value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.