Javascript – How to organize Javascript and AJAX with PHP

javascriptjqueryPHP

My javascript is getting out of hand for my PHP application. I have 20 tags that link to various javascript files in a javascript folder.
Each javascript file basically controls one element on the DOM. And, if the javascript file uses AJAX, then it will have a corresponding PHP file that the AJAX will call.

For example, a js file might control a button on the page:

$(document).ready(function () {
  $("#button").live('click', function() {
    $.ajax({
      type: "POST",
      data: ...
      url: "button_click.php",
    });
  });
});

As you can see, this gets out of hand. What is the best way to organize all of the javascript?

Best Answer

One trick I picked up from a JavaScript library I've been using is to write all my code in separate files but then use a separate "build" script (they used PHP, I use Python, whatever) to "compile" your separate files into a single file and run a minimizer on it.

At first this felt pretty hack-ish, but after just a little while it became quite comfortable. While developing I point the page to the single non-minimized script so that I'll see line numbers while debugging, and then I deploy the minimized script.