 <p>your html is invalid. your <code>&lt;/script&gt;</code> tag should be before the <code>&lt;/head&gt;</code> tag</p> <p>if you really want to execute it only when you press the button then you should consider using ajax or to use a <code>&lt;form&gt;</code></p>