Creating a javascript alert with php that has a php variable inside?

74,183

Solution 1

You only forgot quotations that are required for the JavaScript alert.

If you passed 'hello' to the function, your current code would create alert as:

alert(hello)

instead of doing:

alert("hello")

Therefore, change your line to the following (two double quotes are added before and after concatenating $error):

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

and you can use your function:

died('error on whatever');

Solution 2

Display variable php in alert javascript

   <?php 
          function died($error) { ?>

            <script>alert("<?php echo $error; ?>")</script>

    <?php   die(); 
          } ?>

Solution 3

You can use function follow this:

function died($error) {
    echo '<script> alert("'.$error.'")</script>';
    die();
}
Share:
74,183
MarvinLazer
Author by

MarvinLazer

Front-end/PHP web dev, audio synthesis and music nerd.

Updated on August 16, 2020

Comments

  • MarvinLazer
    MarvinLazer over 3 years

    I'm making a form that is supposed to create a javascript alert when some fields aren't filled out or filled out properly. I want to be able to take the error messages I've put in a php variable and display them in the javascript alert window.

    The following code does not work:

    function died($error) {
        echo '<script type="text/javascript"> alert('.$error.')</script>';
        die();
    }
    

    How can I add the string contained in $error between the two "script" strings so it will output properly as a javascript alert?

    Thank you!

  • MarvinLazer
    MarvinLazer about 10 years
    Thanks! It works, although I don't really understand why. What if I wanted to add other text in the alert that would be concatenated with the variable? Would I have to do something like this? echo '<script>alert('.'Here is some other text!\\n"'.$error.'");</script>';
  • user1978142
    user1978142 about 10 years
    as @frankgorman clearly stated, what happens is that, after you concatenated, you missed the quotes inside rendering the error on javascript. If you want to add, just concatenate another string on $error. Example: $error = "Another Line \n" . $error
  • Eon
    Eon about 9 years
    You know you are very new to a language when you look for ways to alert/log variables :) (happens that I came to search for this answer too)
  • Scarl
    Scarl over 8 years
    This displays nothing. As in it does not display the php variable's value for some reason
  • Crickets
    Crickets almost 5 years
    Your answer did not work for me, but this did: echo '<script>alert("' . $str . '");</script>'; -source
  • Giovanni Esposito
    Giovanni Esposito over 3 years
    Ciao, try to add a small explanation. Code-only answer discourages.