Header does not work

2

Good People,

I have a file in php that is called after completing a form in an html file. The function of this php file is to add data in the database and after inserting it has the following code:

if(mysqli_query($con, $sql)){
	echo "<script>
             alert('Inscrição realizada'); //alerta1
     </script>";
      header('Location: ../register.htm');
	}
	else{
		echo "<script>
             alert('Inscrição não realizada'); 
     </script>";
	 header('Location: ../register.htm');
	 }

But after clicking submit does not show alert1 nor go to the page that I'm telling you to go. Does anyone know how this is resolved? And does anyone know how to go back to the form page but leave the textboxes blank?

    
asked by anonymous 16.06.2015 / 16:50

1 answer

2

Friend, PHP's header x function only works when it is placed before any output to the client.

Ie, codes like this below will result in an error:

<?php

$meus_dados = [1, 2, 3];

foreach($meus_dados as $dado) {
    echo $dado; // saída de dados
}

header('Location: anterior.php'); // Isso resulta em erro pois já houve uma saída

Although not a good practice, if you need to redirect after alert , you can use document.location of javascript.

  if (mysqli_query($con, $sql)) {
      echo "<script>
             alert('Inscrição realizada'); //alerta1
             document.location.href = '../register.htm';
           </script>";

    }
    
16.06.2015 / 17:41