I used to do it with PHP but the problem is that then you can't cache the HTML (varnish or other solutions). Javascript don't have that problem and the added benefit of stopping bots that don't run javascript.
In the error message I have a friendly texts for human to turn on javascript if it is off and a <a href="javascript: history.go(-1);">Go back and try again</a> making them not loose the text that they have typed.