Alert is not displayed when I show it before a redirect

0

I want to show a message with the error generated by a sentence in my BD and then redirect to another page, the code is as follows:

echo '<script language="javascript">alert("Error al Grabar Cheque:'.$arr[2].'");</script>';
sleep(5);
header('Location: index.php?controlador=ChequesController&accion=Listar');

$ arr [2] contains the error message, I even put the sleep to delay the execution of the redirection and the error can be seen. (I can only see the message if I remove the Header line). Any suggestions? Thanks

    
asked by Emersoft 25.10.2017 в 20:48
source

2 answers

1

If the response deveulve as status code HTTP 302 redirect, then the whole body of the response, in this case all the HTML will be discarded and the redirection will simply be made to the destination page.

The sleep will not achieve anything because it runs on the server and not on the client.

What you must do is return your HTML with a setTimeout and after the time interval has passed do the redirection by JavaScript, and without returning any header.

Example

echo '<script>';
echo '    alert("Error al Grabar Cheque:'.$arr[2].'");';
echo '    window.setTimeout(function() {';
echo '        window.location.href ="<url destino>";';
echo '    }, 5000);';
echo '</script>';
    
answered by 25.10.2017 / 21:09
source
0

Depending on the PHP engine (Apache with modphp, Apache with fastcgi, Nginx with php-fpm) PHP may or may not write all the content once instead of printing it as you put echo.

If not, you could use flush

echo '<script language="javascript">alert("Error al Grabar Cheque:'.$arr[2].'");</script>';
flush();
sleep(5);
header('Location: index.php?controlador=ChequesController&accion=Listar');

but maybe that does not work for you and you do a lot of laps using other PHP options. (See this answer in StackOverflow where they ended up modifying the php.ini to that will work)

I would do everything with javascript.

echo '<script>';
echo 'alert("Error al Grabar Cheque:'.$arr[2].'");';
echo 'window.setTimeout(function() { window.location.href="index.php?controlador=ChequesController&accion=Listar";   },5000);';
echo '</script>';
    
answered by 25.10.2017 в 20:54