I think you are fundamentally confused about the page lifecycle of PHP versus JavaScript.
PHP is a server-side scripting language. When you request a page from your server (by navigating to it, or initiating an AJAX call), the PHP script runs from start to finish and your server returns its output (which in this case is an HTML page). That's it. PHP is done when the page source is delivered to your browser.
JavaScript, on the other hand, is a client-side scripting language. JavaScript operates inside your browser and can make changes to a page once the page is loaded (most notably by altering the DOM).
AJAX provides a somewhat tenuous link between the two worlds. Javascript functions like the .post() in jQuery send an asynchronous request back to the server and tell the server to retrieve a certain file. If that file is PHP, the server typically executes it.
So in your example here's what happens:
- You type the URL for thefilename.php into your browser and hit
enter
- Browser sends a request to the server for thefilename.php
- Server recognizes thefilename.php as a PHP file and tells PHP to
execute the script
- The PHP script runs. Its output is determined by the data contained
in the request body ($_POST in PHP). It outputs some HTML code.
- The server responds to your request for thefilename.php with the
HTML code produced by executing it.
- Your browser renders the HTML code for you.
- You click the button
- JavaScript in your browser sends a request to thefilename.php on
your server
- Your server recognizes thefilename.php as a PHP file and tells PHP
to execute the script
- The PHP script runs. Its output is determined by the posted
data. It produces some HTML code.
- The server responds to your request for thefilename.php with the
HTML code produced by executing it.
- The .post function receives the HTML response and then renders it
inside an alert.
I hope that helps explain what's going on.
Most likely you want a separate PHP file for your asynchronous call.