Frage

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!

War es hilfreich?

Lösung

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 code to the following (json_encode() the string and create a javascript variable out of it):

function died(string $message) {
    if ('' === trim($message)) {
        $message = 'died.';
    }
?>
    <script type="text/javascript">
      var message = <?php echo json_encode($message); ?>;
      alert(message);
    </script>
<?php
    die();
}

and you can use your function:

died('error on whatever');

Andere Tipps

Display variable php in alert javascript

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

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

    <?php   die(); 
          } ?>

You can use function follow this:

function died($error) {
    echo '<script> alert("'.$error.'")</script>';
    die();
}
<?php
 echo "<script type='text/javascript'>alert('{$_SESSION["success"]}');</script>";
 unset($_SESSION["success"]);
?>

Use this code it would work correctly

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top