I am getting a really weird JavaScript error when I run this code:
<script type = 'text/javascript'> var ask = confirm('".$message."'); if (ask == false) { return false; } else { return true; } </script>
In the JavaScript console it says:
Syntax Error: Illegal return statement
It occurs at return true;
and return false;
(I am echoing this javascript from a php function; the $message
variable is one of the php parameters)
What is wrong with my code?
The "Illegal return statement" error occurs when the return statement is used outside of a function. To solve the error make sure to only use the return statement inside of a named or an arrow function. The statement ends a function's execution and returns the value to the caller.
The return and yield statements must be in a function, because they end (or pause and resume) function execution and specify a value to be returned to the function caller.
return
only makes sense inside a function. There is no function in your code.
Also, your code is worthy if the Department of Redundancy Department. Assuming you move it to a proper function, this would be better:
return confirm(".json_encode($message).");
EDIT much much later: Changed code to use json_encode
to ensure the message contents don't break just because of an apostrophe in the message.
If you want to return some value then wrap your statement in function
function my_function(){ return my_thing; }
Problem is with the statement on the 1st line if you are trying to use PHP
var ask = confirm ('".$message."');
IF you are trying to use PHP you should use
var ask = confirm (<?php echo "'".$message."'" ?>); //now message with be the javascript string!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With