Page 1 of 1
Calling javascript from inside PHP?
Posted: Mon Apr 27, 2009 8:08 pm
by raydona
Hi,
How can I jump (redirect) to another page after say 6 seconds from inside PHP code. For example, I wish to say:
Code: Select all
$sql = "some code";
if(mysql_query($sql))
{ echo "Successful<br/>";
//redirect to page A after 6 seconds
}
else
{ echo "Unsuccessful";
//redirect to page B after 6 seconds
}
The only way I know how to redirect to another page after some time is using javascript.
<script type="text/javascript">
function timedMsg()
{ var t = setTimeout("location.href='file.html'",6000);
}
</script>
But how can I write javascript inside PHP code? I would be very grateful for all help.
Re: Calling javascript from inside PHP?
Posted: Mon Apr 27, 2009 9:04 pm
by Christopher
PHP is a language designed to generate HTML pages. Anything added to the output by echo() and header(), and anything outside of the <?php ?> tags will be sent to the browser.
Re: Calling javascript from inside PHP?
Posted: Tue Apr 28, 2009 4:54 am
by Yossarian
Make sure you have previously echoed absolutely nothing to the browser, not even a blank line or a space.
If so, as I understand it you can then sleep() for x seconds and redirect using php's header() command something like this;
Code: Select all
if(something-bad) {
sleep($time);
header( 'Location: ' . $location );
exit();
}
I've never used sleep before, so try it without first off.
EDIT
I am not at all sure that is what you want to do though, if you want to show a six second message then your should redirect to six-second-message.htm which contains a html meta tag redirect, or the js timer and redirect.
Re: Calling javascript from inside PHP?
Posted: Tue Apr 28, 2009 5:33 am
by user___
Why do not you try META?
<meta http-equiv="Refresh" content="[time]; URL=[some-url]">
Re: Calling javascript from inside PHP?
Posted: Tue Apr 28, 2009 10:40 am
by theo13
user___ wrote:Why do not you try META?
<meta http-equiv="Refresh" content="[time]; URL=[some-url]">
Are you sure it will work with META?( I personally try to avoid it- if it works it would be an alternative)
The easiest way(not necessarily the best) is to call javascript is simply to use echo within the php code.
Re: Calling javascript from inside PHP?
Posted: Tue Apr 28, 2009 10:44 am
by user___
Yes, I am sure it will work, but I can not say the same for the JS solution, because if a client has his/hers JS off, no redirection will be made.