views:

57

answers:

3

Often I add helper functions to my PHP that return complex HTML. For example, it is not an easy task to ensure that a form element is accessible, can handle errors etc. and so I will have a PHP function wrap this problem.

Unfortunately, sometimes, I will need to generate the same HTML but with JS instead. An example of this is where I have a Flash uploader which uploads multiple files. As each file is uploaded, I want to populate another form on the same page which will allow the user to edit the files data.

I already have the specification for the inputs for this form in PHP helper functions. At the moment, I just recreate these inputs manually with JS. However, this is inefficient and frustrating because if I wish to change some aspect of these inputs, I now have to change them in two places.

One thing I could do is pass the form elements back to JS in the same AJAX request which uploads the file. This works fine but could be problematic if I have large amounts of HTML.

Is there a better way than this or is using the AJAX request the best it gets?

A: 

Make a page/controller in your php, that will be given a reference to the specifications you have stored, and will call the function and send back it's output.

Then you make an ajax call when required, that will request the page with the required parameters to get the wanted content.

aularon
A: 

Half-way through your answer I was going to suggest grabbing the inputs as JSON via a web service. In other words, I was going to suggest AJAX (or AJAJ I guess).

I do not see how you would coordinate the content otherwise.

Justin
+3  A: 

One thing I could do is pass the form elements back to JS in the same AJAX request which uploads the file. This works fine but could be problematic if I have large amounts of HTML.

Certainly, this would allow you to avoid the code duplication.

But if you're just requesting identical HTML twice, that means - regardless of the size - there's an additional HTTP request for the same data.

It's probably not a big deal, but if you're that concerned, use AJAX to request the data once, store the result, then just used the 'cached' HTML next time you need to add an element.

Of course that only works if the HTML is identical.

Now if it is identical, and if the initial request puts one copy on the page, why not skip the AJAX request, and just have the javascript 'cache' a copy of the form when the document is loaded? Then you can duplicate the original form each time it's needed.

Tim Lytle