How to call a javascript function script from php - Stack Overflow
Move your PHP after the JS function. PHP will parse the entire page and deliver it to the browser, where the JS is then evaluated. The problem you're having above is that the page that's delivered to the browser tries to execute a function that hasn't been created yet.
Source: stackoverflow.com