dopatraman
dopatraman

Reputation: 13908

Rendering javascript code in php document

I'm a beginner to PHP and I have a quick question. Is it possible to have javscript code injected into a document through php?

For example, suppose I wanted to inject a button that called a function after a form is filled out:

<html>
<head>
  <script type = text/javascript>
  function func() {
  ...
  }
  </script>
</head>
<body>

<form action = 'welcome.php' method = 'post>
Name: <input type = 'text' name = 'fname' />
<input type = 'submit' value = 'submit' />
</form>

<?php
if (isset($_POST['fname'])) {
   echo '<input type = button onclick = func />'
}
?>

</body>
</html>

Would this work? If not, why not?

Any help would be great

Upvotes: 0

Views: 177

Answers (3)

Manse
Manse

Reputation: 38147

Will work fine - just remember to close your quoted strings :

<form action='welcome.php' method='post'> // add ' here
Name: <input type='text' name='fname' />
<input type='submit' value='submit' />  // removed a couple of spaces (not required)
</form>

<?php
if (isset($_POST['fname'])) {
   echo '<input type="button" onclick="func" />';   // added some quotes and a semicolon
}
?>

I have removed the spaces between the attributes and the values in HTML from type = "something" to type="something" although I can't find the "official" specification on this. It seems that the spaces are perfectly valid ...I think its my personal preference to have no white space there .....

Upvotes: 1

Matt H
Matt H

Reputation: 6532

Try:

echo '<input type="button" onclick="' . $_POST['fname'] . '" />';

SAMPLE

If fname=doSomething then use:

echo '<input type="button" onclick="' . $_POST['fname'] . '()" />';

and your rendered HTML would be:

<input type="button" onclick="doSomething()" />

Then you'd just need your function somewhere:

<script>
  function doSomething() { }
</script>

Upvotes: 0

Blender
Blender

Reputation: 298196

If your current page is welcome.php and you ran this code, you would press the Submit button and the page would reload and have your new button.

But the best way to see whether this works for you or not is to run it. Why don't you try that first?

Upvotes: 0

Related Questions