Any tips to make dynamic javascript creating PHP code look cleaner?

I do this ALL the time. My PHP system generates html, css and a lot of javascript and sends it all to the browser. Then as the user moves around the webpage in the browser they can initiate AJAX updates which call back the server with requests for new data or requests to save data the user input.

My system is typically a menu running one of about 20 or 30 single page applications. So one application might be user management which allows new users to be added, profiles to be changed, passwords to be updated etc, Another module might be contract management which allows users to enter, maintain and delete contracts. Each of these modules is a separate SPA.

Now the initial PHP can just use normal script tags to include your JS files. I like to use a literal object for each SPA and then a number of literal objects for utility functions. I also dynamically load most of my html (so I can use different skins for different locations and for different customers). So my PHP stub looks like this:

include config-files, error-handler, db-handler, autoloader, session-handler
if (!logged_in)
    redirect to login; die;
load base JS files (jquery)
load base CSS files (global UI)
load base html container (just anempty container and noscript element)
echo <<<EOS

<script> $.when (jquery.load(container, $this_page_skin) ) .then ( ui_thispage.init(); ) </script> EOS;

Thats it. Now the front-end takes over. All ajax calls from the front-end are routed through a single do_ajax_call.js file which in turn sends all requests to a back-end do_ajax.php file. The back-end processes the request type, calls various back-end classes to deal with it and sends any subsequent data back to the js file. The js file processes the callback data, logs the interaction and sends the data back to the view function to update the view with new data.

This is all very simple and easy to follow. I hope it helps. If you want more detail on how to set this up just ask.

FYI, for this type of system I don't use a JS framework as they just slow everything down, especially on mobile screens. This is vanilla javascript and jquery (for cross-browser compatibility).

/r/webdev Thread