This is not the problem of coding. This is the problem with what PHP can do and cannot do and when.
PHP is server side programming and if you want an answer in the user screen with some field calculation you don't need any PHP.
See my code and that should do the job for you. All you have to do is make sure you make that code appear in the right event handler.