Go Back via JavaScript and PHP

by Jeff Starr on Monday, March 12, 2007 5 Responses

Use this simple code as a button that will return users to the previous page:

<form>
 <input type="button" value="Return to previous page" onClick="javascript:history.go(-1)" />
</form>

Here it is as a simple text link:

<p>
 <a href="javascript:history.go(-1)" title="Return to the previous page">&laquo; Go back</a>
</p>

You can make things easier by serving PHP and printing the link automatically. Here is the button link:

echo "<form><input type=\"button\" value=\"Return to previous page\" onClick=\"javascript:history.go(-1)\"></form>";

And here is the PHP code to print a "Go back" text link:

echo "<p><a href=\"javascript:history.go(-1)\" title=\"Return to previous page\">&laquo; Go back</a></p>";

Better yet, you can kick the accessibility factor up a notch by using PHP’s inherent HTTP_REFERER variable to write explicitly the previous URL, thereby eliminating the JavaScript requirement (thanks to Rick Beckman for the idea):

<?php $referer = $_SERVER['HTTP_REFERER'];
   if (!$referer == '') {
      echo '<p><a href="' . $referer . '" title="Return to the previous page">&laquo; Go back</a></p>';
   } else {
      echo '<p><a href="javascript:history.go(-1)" title="Return to the previous page">&laquo; Go back</a></p>';
   }
?>

The previous code will create an explicit "Go back" link when the referring URL is known. In those awkward situations where no referring URL has been recognized, the function writes a "Go back" link via JavaScript.

About the author

[ Jeff Starr ]

Jeff Starr is a web developer, graphic designer and content producer with over 10 years of experience and a passion for quality and detail. Jeff is co-author of the book Digging into WordPress and strives to help people be the best they can be on the Web. + Follow Jeff on Twitter and subscribe to Perishable Press for quality web-design content delivered fresh.


5 Responses
[ Gravatar Icon ]

Rick Beckman#1

If you are using PHP for it, wouldn’t it be easier to catch the referral URL, if present, and then presenting the link with an actual URL pointer, rather than JavaScript? Accessibility would be helped quite a bit then.

If no referral URL is set (some users turn it off), a JavaScript-based fallback could be used.

[ Gravatar Icon ]

Perishable#2

Of course, of course … I was just testing you ;)
Check out the new, improved version of the article to see your idea in action.
- Thanks for the catch!

[ Gravatar Icon ]

Rick Beckman#3

You’re welcome!

[ Gravatar Icon ]

stamyo#4

thank you for the info! works fine…

[ Gravatar Icon ]

Perishable#5

Happy to help!

Comments are closed for this post

If you have or need further information, contact me.



Attention: Do NOT follow this link!