1

Hi i have to set a message box with time out when a specific data is already available in the database table.and then redirect to another page.My issue is that when page is getting redirected without showing the alert box.

Control statements php:

$count=0;
$sql="SELECT main_sec_name from main_sec_temp";
if($r=mysqli_query($con,$sql)) {
    while($result= $r->fetch_row()) {
        $count=$count+1;        
    }
}   
if($count==0) { 
    if(mysqli_query($con,"INSERT INTO main_sec_temp(main_section_order,main_sec_name,main_number_of_ques,attempts) VALUES('','$sec_name','$no_question','$no_attempts')")) { 
        echo "Successfully Inserted";          
        header("location:index.php");       
    }else{        
        echo "Insertion Failed";        
    }
} else { //When Data is already exist 
    echo "<script>alert('already exist')</script>";
    header("location:index.php");   
}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Tamil
  • 25
  • 12

1 Answers1

0

You are trying to mix server side (PHP) and client side (Javascript) code in your example. Using header('Location:...') will get executed by PHP before the user will get a chance to see the contents of the page (also headers need to be used before any content is displayed on the page).

Additionaly, using javascript alert() requires user interaction by pressing the OK button, so you can't use timeout to redirect user.

Better approach would be something like this:

/// display html message and   the javascript part of your code
echo "<h3 class='error'>Already exist</h3>";
echo "<script>";
echo "setTimeout(function(){ ";
echo "   document.location='index.php';";
echo "}, 3000);";  // redirect after 3 seconds
echo "</script>";         
mike_t
  • 2,484
  • 2
  • 21
  • 39