Using PHP Data in JavaScript Functions

I recently built an autocomplete function (using JavaScript) for a publications tracking application which allows users to enter part/all of a tag into an input field and it will automatically suggest completions which can be done as many times as the user wants if they want multiple tags [think Flickr] assigned to a given record. The data which powers the autocomplete method is coming from a PostgreSQL database so I had several ways of approaching the problem. My first instinct was to use an ajax call to pull back the data and store it in a JavaScript array but then I got to thinking … In the same script (in a PHP block) I already had a handle open to the database I needed to query so I went ahead and did the query there, grabbed the results, used a nested foreach() loop to build up a string of all the data elements which I then simply echo out later in my JavaScript code by breaking into a PHP block.

This approach not only saved me a bit of programming time but also from putting any undo stress on the client by letting the server do all of the work. In many cases this approach won't be ideal but when you are working with data that exists exclusively on the server and don't need to do anything other than output it, I would recommend using this approach to save time and resources on the client side.