I feel your pain. But then I had such a debug nightmare with runtime script additions that I decided on another method.
This is an example of how I work it, in this case using buttons.
Instead of having static menu buttons in the code, I put a single button function and use runtime info to let my php know what button it is responding to and any page parameters your application needs. This is likely to be a minimum of a page id and section id. Not a button id, because the purpose of this method is to allow dynamic addition of buttons. Only your php needs to alter it's action for any additional buttons you add.
<script type="text/javascript" >
$(document).ready(function(){
$("button").click( function() {
$.get( "/menu_to_body_respond.php", {
pageId: $thisPageId
subSecID: $thisSubID
}, function( resp ) {
$("#left_body").html(resp);
});
});
});
</script>
Then do what ever you want with the section in your php function
menu_to_body_respond.php
<?php
$pageIDVal = $_GET[ 'thisPageId'];
$subIDVal = $_GET[ 'thisSubId'];
// code to decide what to do with this button press
// switch statements do a good job, if your
// application has a lot of items you might want to respond to
//just put the most used items at the beginning of the switch.
//tmp code to give you a response
$outStr = $pageIDVal . " Left Body B2";
echo($outStr);
?>
You can of cause mix it up, have buttons that are responded to locally such as the general menu open/collapse and basic client side work. Just have the id named buttons first, and if one of those could respont they stop the $('button') running simply with an if-else statement.