The normal way to handle this synchronously (that is, without AJAX) would be to add a redirect back to the page you came from at the end of your script (call the redirect()
function).
If you want to do this asynchronously (so the user never actually leaves the page when they press the button), you'll need to implement a Web Service function to run your server-side code, write an AJAX call to the web service, and package it as a Javascript module. That's quite a lot to learn, but it's all valuable stuff to know.