tags:

views:

168

answers:

2

Here's a situation which I have encountered, creating a form on the client side and using PHP to process. Here are some considerations

  1. The PHP script generates the form and send to the client side. This is because of internationalization issues
  2. The client side uses JavaScript to submit form; the ID of the form is hard-coded inside the JavaScript as it is generated by PHP. This means everytime the PHP code is updated, the JS must change.

The question here is, who should be dependent on who? Should the JS generate the form instead, so that the PHP script has to know the names of the form elements? OR should it be the other way round?

A: 

PHP should generate the Form + a hidden field with the ID of the Form. then the javascript submits the form.

Thats how I would do it...

xXx
A: 

If the Form is being generated from the PHP Script, then it should be easy to (as @xXx suggested) have that script add the relevant ID to the form for later processing. Whether that ID is added as an "id" attribute for the "form" element, or as a hidden "input" field would be dependent on a number of factors.

The Javascript, rather than needing a hard-coded value within itself, should be configured to (if needed) find the ID within the form, as set by the PHP Script above.

Of course, this advice is a little airy-fairy as I have no idea how your solution has been designed.

But, for some visual aids:

In the PHP Script creating the Form

<?php
//After the Form open tag has been echo'd
//Assuming $formID is the Form's ID
echo '<input type="hidden" name="formID" value="'+$formID+'">';
?>

Which would create something like

<form ... >
  <input type="hidden" name="formID" value="1234">
  ...
</form>

And then the Javascript should be able to do something like

//Assuming Javascript variable "targetForm" is pointing at the above form object
formID = targetForm.formID.value;
Lucanos