mr_mohapatra
mr_mohapatra

Reputation: 17

why wont javascript show the alert?

beginner here. I do not understand why no alert pops up when I use the header statement,but the alert pops up just fine when I remove the header location line. Really confused :(

<?php
include "connect.php";
session_start();
// if(isset($_SESSION['user_id'])
if(isset($_POST['register'])){
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
$name=$_POST["name"];
$roll=$_POST["roll"];
$year=$_POST["year"];
$pass=$_POST["register_password"];
$sql="INSERT INTO students (roll_id,name,year,password) VALUES 
('$roll','$name','$year','$pass')";
$query=mysqli_query($conn,$sql);
if(!$query)
{
   echo "Not Inserted" . mysqli_error($conn);
 }
 header("location:index.php?registered=true");
}
?>

Upvotes: 0

Views: 64

Answers (3)

Blue
Blue

Reputation: 22911

The problem is header() needs to be sent before ANY output in order to redirect the page to another URL. At that time, you're already echoing things out, so redirects via headers wont work.

In a case such as this, (Where you want to popup a message and then redirect), you should use a javascript redirect:

echo '<script language="javascript">';
echo 'window.location.replace("/index.php?registered=true");';
echo '</script>';

This will output your popup message. After the user hits OK, the javascript redirect code will run, and redirect the page to /index.php?registered=true.

Additionally, you can add the alert box to the page that you're redirecting too. See this example index.php file:

<?php

if (isset($_GET['registered'])) {
    echo '<script>alert("You have registered!");</script>';
}

//Continue with rest of page.

If you go this route, don't include ANY output (No echo) on the register page, so that header()s are your only output. This would ideally be a better user experience, as they don't have a white popup page as they're clicking a box that says alert("message successfully sent").

Upvotes: 1

James Baloyi
James Baloyi

Reputation: 82

Echo it like this:

echo "<script>alert('message sent'); window.location.href='url';</script>";

Upvotes: 0

EvE
EvE

Reputation: 750

This is because the location header redirects to a different page before the JavaScript alert is shown.

Add the alert to the destination page and it will be shown there.

Upvotes: 1

Related Questions