Reputation: 1177
As I am new to this I would like your advice.
So far I have figured out two ways to populate form fields.
Say this is my html:
<input id="test" name="test" type="text">
As you see the id of each field matches the name.
When it's time to populate the field from Sql i could either do:
PHP:
<input id="test" name="test" type="text" value="<?php if(isset($SqlRequested['test'){echo $SqlRequested['test'];}">
and similarily write all the fields of my form...
or add this in the head part
JQUERY:
<script>
<?php echo "$(document).ready(function(){";
foreach ($SqlRequested as $id => $value){
echo "$('#" . $id . "').val(\"" . $value . "\");"
echo "};"
echo "});"
?>
</script>
besides the fact that the jQuery gives me some problems when the fields contain "enter/return" in them (which could be fixed by using .html or .text i guess)
Which one would you suggest, what are the drawbacks or pro's of each method?
Any improovements to the code?
Is there some other way i am missing?
Any suggestions on easily fixing the little problem mentioned above?
Thanx in advance.
Edit: I just noticed the jQuery .populate, which im guessing is something like my second way, you just need to get your data in a format of {'id':'value',...}
Upvotes: 0
Views: 1958
Reputation: 5349
You should use PHP to render the page as someone without javascript wouldn't get the values of your javascript version.
PHP: Pros: All browsers will get what you want them to get. The output HTML is arguably more correct as it has the value that the user expects in it
Cons: ...Increased server load....by such a small amount that it should probably not even be a con
JS: Pros: ...
Cons: Non JS enabled browsers won't see the values you expect.
Improvements: Write a function in PHP that will auto echo your value if it exists to cut down on duplicate typing. Something like:
function echoValue($value) {
global $SqlRequested;
if(isset($value)){
echo $value;
}
}
Or if you wanted:
function echoValue($value) {
global $SqlRequested;
if(isset($SqlRequested[$value])){
echo $SqlRequested[$value];
}
}
Upvotes: 3
Reputation: 436
Nice question - all of this methods using in different frameworks, cms etc. Most "simple" and direct method is
value="<?php echoValue('test');?>"
Most powerful and "complex" is use framework like knockout.js for render forms.
And yes - "Who wouldn`t have javascript?"
Axiom - All have javascript.
Upvotes: 0