Hope is I will break the page up before I need to do this but regarding the "onload=" am I to understand that the backslashes and quotes should be placed as you've defined them or is it just quote quote? I am new to this and will be for some time.
To make this only happen when the validations fail you could add a php if statement around the body onload event like this:
<body <?php if(isset($_POST['invalid']) && $_POST['invalid'] == 'true') echo "onload=\"the js code here\"" ?> >
This should get that part of the page to load so long as the js code works correctly. Make sure you get that part working before you attempt to add in the php code.