2

How can i write a javascript alert inside php ? For example if i want to popup a javascript alert in this if condition how I can do it ?

if(isset($_POST['downloadkey'])){
                $key = $_POST['downloadkey'];
                if($key != $data['download_key']){
                    echo 'Your key is wrong.';
                    echo '<script type="text/javascript"> alert(Your downlaod key is wrong, Please try again!);</script>';
                }
            }

Thanks in advance

10
  • why is this snippet not working? on a roughly base the alert should appear if both if conditions are true. Do you render these two lines inside a valid html page? Commented Mar 27, 2012 at 12:39
  • 4
    Does the code you posted work? What happens when you run it? (There is a typo in the code, first of all. The string in the alert() needs to be wrapped in quotes.) Commented Mar 27, 2012 at 12:39
  • tough typo, haven't even seen it (credits should go to David! :)) Commented Mar 27, 2012 at 12:43
  • 2
    Why do you want to invoke JavaScript when you are already on the server side? Commented Mar 27, 2012 at 12:44
  • @Daxcode: Of course, if the OP simply runs the code, an error message would point out the same thing :) Commented Mar 27, 2012 at 12:45

2 Answers 2

5

You forgot to wrap string with quotes in alert .

"Your downlaod key is wrong, Please try again!" is a string

if(isset($_POST['downloadkey'])){
                $key = $_POST['downloadkey'];
                if($key != $data['download_key']){
                    echo 'Your key is wrong.';
                    echo '<script type="text/javascript"> alert("Your downlaod key is wrong, Please try again!");</script>';
                }
            }
Sign up to request clarification or add additional context in comments.

6 Comments

is it possible i remain on the same page with reloading it ?
@FaryalKhan If you are not redirecting to anywhere else , it will stays in same page
in my if condition i now added $again=1 and when I load the page it says undefined variable again why?
If condition is not satisfied your $agree will not set anymore
an if the condition is satisfied and i want to send that variable from one php file to another how can i do that ?
|
0

You can do this by putting this alert into the onload of the body like so:

<body onload="alert('Your download key is wrong, Please try again!');">

...


</body>

Comments

Your Answer

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.