1

I'm trying to pass a string variable through the parameter of a php function called alertText to a javascript function called alert, to alert a message to the screen, but it's not accepting the php variable for some reason, and nothing is being alerted to the screen. Please take a look:

testing.php

function alertText($text) {

echo "

<script>
alert($text);
</script>

";

}

alertText("Hello");

?>

4 Answers 4

1

You need to single-quote the $text variable, because JavaScript is not recognizing that variable as string.

<?php 
function alertText($text) {
    echo "<script>alert('$text');</script>";
}
alertText("Hello");
Sign up to request clarification or add additional context in comments.

Comments

1

You could concatenate it to get a more readable code.

function alertText($text) {
    echo "<script>alert('".$text."');</script>";
}

alertText('Hello');

Comments

1

Very simple mistake, you forgot to close the double quote letting the parser know that $text is not the word $text (hey it could happen!).

We use .$variable_name. to concatenate the value of the variable with the javascript function at runtime.

   <?php

   function alertText($text) {

    echo "
       <script>
         alert('".$text."');
       </script>
    ";

    }

    alertText("Hello");

    ?>

** EXAMPLE CORRECTED **

Comments

1

You should use it like

    function alertText($text) {
echo '<script type="text/javascript">alert("' . $text . '"); </script>';

";

}

alertText("Hello");

?>

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.