How can Javascript window.location.href and window.alert can work together inside if else cycle?
I have the following code to insert data inside an SQL table. If something wrong, a notice message appear (Notice: Undefined variable: code1 in......) for just a second because of window.location.href redirection and the alert (messagebox) don't appear.
if(isset($_POST['add_item'])){
$edit_id = $_POST['edit_id'];
$code = $_POST['code'];
$sql = "INSERT INTO table (code)
VALUES ('$code1')";
if ($conn->query($sql) === TRUE) {
echo '<script type="text/javascript">window.location.href="page.php"</script>';
} else {
//echo "Error: " . $sql . "<br>" . $conn->error;
echo '<script type="text/javascript">alert("Error: ' . $sql . "<br>" . $conn->error .'")</script>';
}
}
$code1 inside VALUES into $SQL was deliberately placed to generate the error. Is there a way to redirect if all is OK and open the messagebox if an error appear
You could simply use
header()
on server side if you want to forward:BTW: don't forget semicolon terminating each line…
AND USE PREPARED STATEMENTS!