This is server-side code, and will run when the page is being "rendered" in server to be sent to the client.
Maybe you could create a logout page that remove the user session and then redirects him to the index page or you could do the session logout through an Ajax call.
What you need to have in mind is:
PHP -> server-side code
and that client and server code don't have direct access to each other.
Hope it helps.