Cthulhu Cthulhu - 3 years ago 201
PHP Question

Javascript Redirect in php if else statement

I have the below javascript function:

function pageRedirect() {
window.location.replace("ProdTypes.php");
}
setTimeout("pageRedirect()", 3000);


in a PHP if else statement (see below):

if($ptRowCount > 0) :
if ($ptQTYRowCount > 0):
$errors[]='Cannot delete or Archive product which has a Product Quantity > 0!!! Refreshing Page in 3 seconds...';
?>
<script>
pageRedirect();
</script>
<?php
elseif($ptQTYRowCount == 0):
$sql = "UPDATE producttype SET ProdTypeArchive='1' WHERE ProductTypeID = '$delete_id'";
$_SESSION['success_flash']='Product Type was Archived succesfully';
endif;
else:
$sql = "DELETE FROM producttype WHERE ProductTypeID = '$delete_id'";
$_SESSION['success_flash']='Product Type was deleted succesfully';
endif;


I require that the javascript counter only comes into action in the if statement where
if ($ptQTYRowCount > 0):


At the moment it is realoading the page even when the if statement is not triggerred.

Anyone can help please?

P.S. I do not want to use Header for redirection. WHen I use headers I have the below error:


Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\aresV2\admin\includes\navigation.php:48) in C:\xampp\htdocs\aresV2\admin\ProdTypes.php on line 51

Answer Source

It is unclear from your question, but if you include the entire block of code in your page (the function + setTimeout statement), this causes the page to always reload after 3 seconds.

The solution would be to remove the setTimeout line, and in your if statement replace

?>
<script>
    pageRedirect();
</script>
<?php

with

?>
<script>
    setTimeout("pageRedirect", 3000);
</script>
<?php

As for the error you get when trying to redirect using headers, this has been answered before here on SO

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download