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

MarvinLazer picture MarvinLazer · Apr 28, 2014 · Viewed 62.6k times · Source

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!

Answer

user1978142 picture user1978142 · Apr 28, 2014

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');