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");
?>
asked Jun 18, 2015 at 2:38

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");
answered Jun 18, 2015 at 2:49
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');
answered Jun 18, 2015 at 2:50

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 **

answered Jun 18, 2015 at 2:50

Comments

1

You should use it like

 function alertText($text) {
echo '<script type="text/javascript">alert("' . $text . '"); </script>';
";
}
alertText("Hello");
?>
answered Jun 18, 2015 at 2:53

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.