I found AJAX very confusing when I started looking at it. One thing
that really confused me was code like the following example (from
administrator/components/com_finder/controllers/indexer.json.php):
// Send the JSON response.
echo json_encode($response);
// Close the application.
JFactory::getApplication()->close();
The key to understanding this code (at least for me) was to understand
that this PHP program was being called from a JavaScript program. The
JS program is waiting for a JSON encoded string to be echo'd and then
the JS program will read that string and continue it's processing
after the PHP process closes.
I still find the ways in which JS and PHP interact to be a bit
mysterious and confusing, but at least this helped me understand it a
bit better.
If you look at the Joomla installation, which uses AJAX, or this
example from com_finder, and carefully trace through the
back-and-forth between PHP and JavaScript, it might help you.
Good luck. Mark