satya
satya

Reputation: 3560

Can not display alert message using PHP

I have one issue while trying to display alert message using PHP.I am explaining my code below.

<?php
if($id){
      $message = "Added successfully.";
      echo "<script type='text/javascript'>alert('$message');</script>";
      header("location:http://localhost/crm_complain/index.php");
  }else{
      $message = "Unable to add.\\nTry again.";
     echo "<script type='text/javascript'>alert('$message');</script>";
      header("location:http://localhost/crm_complain/index.php");
  }
?>

Here my problem is the alert message box is not working at all.I need inside the if/else condition the alert message should work.Please help me.

Upvotes: 0

Views: 415

Answers (2)

devpro
devpro

Reputation: 16117

You can not get alert as like that because you are using header(). You can resolve this as:

Your PHP Code (pass success status):

<?php
if($id)
{
    //$message = "Added successfully.";
    header("location:http://localhost/crm_complain/index.php?success=1"); // success status
}
else
{
    //$message = "Unable to add.\\nTry again.";
    header("location:http://localhost/crm_complain/index.php?success=0"); // failure status
}
?>

You need to add following code in index.php file for getting alerts:

<script type="text/javascript"> 
    var phpVar = "<?php if(isset($_GET['success'])) {echo $_GET['success'];} else { echo ""; } ?>";
    if(phpVar == 1){
        alert('Added successfully.');
    }
    else if(phpVar == 0){
        alert('Unable to add.\\nTry again.');   
    }
    else{
        // nothing
    }
</script>

Upvotes: 0

Erik Kalkoken
Erik Kalkoken

Reputation: 32697

The alert message works fine, but the header does not. If you want to redirect after the alert message, try this:

die('<script>location.href = "'. $url .'"</script>');

Upvotes: 1

Related Questions