Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 689
MarvinLazer Avatar asked Apr 28 '14 01:04

MarvinLazer


People also ask

How do you alert a variable in JavaScript?

Type "alert ("Hey, " + name + "!");". This line of code will add the variable "name" to the word "Hey, "(with the space at the end), and then add "!" to end the sentence (not required). For example, if the user inputs "Trevor" as the value of the variable "name", the alert will say "Heya, Trevor!".

Can I use alert in PHP?

PHP doesn't support alert message box because it is a server-side language but you can use JavaScript code within the PHP body to alert the message box on the screen.

How use JavaScript confirm box in PHP?

Confirm dialog box displays a predefined message with two buttons: OK and Cancel buttons. The user will have to click either of the button to proceed. If the user clicks an OK button, the box returns true to the program. If the user clicks the Cancel button, the box returns false to the program.

Can I use JavaScript variable in PHP?

The way to pass a JavaScript variable to PHP is through a request. This type of URL is only visible if we use the GET action, the POST action hides the information in the URL. Server Side(PHP): On the server side PHP page, we request for the data submitted by the form and display the result.


3 Answers

Display variable php in alert javascript

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

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

    <?php   die(); 
          } ?>
like image 142
antelove Avatar answered Nov 07 '22 11:11

antelove


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');
like image 36
user1978142 Avatar answered Nov 07 '22 11:11

user1978142


You can use function follow this:

function died($error) {
    echo '<script> alert("'.$error.'")</script>';
    die();
}
like image 31
user3571318 Avatar answered Nov 07 '22 13:11

user3571318