Reputation:
I dont know much about PHP functions.I want to print the name inside the function when it is called on clicking the button.I have tried different ways and even searched for it in google.Need help...
<?PHP
function writeName()
{
echo "Kai Jim Refsnes";
}
Echo "<form>
<input type='button' onClick='writeName();' style='position:fixed;bottom:0px;left:0px;width:100%;'>
</form>";
?>
Upvotes: 1
Views: 87
Reputation: 6787
I can provide you with three alternatives:
1. Using pure PHP.PHP is server-side
Changes in pure PHP takes place in the following way
So using pure PHP i can figure out only one way to call function on button click.I can be done as follows:
<?PHP
function writeName()
{
echo "Kai Jim Refsnes";
}
if(isset($_GET['submit']))
{
writeName();
}
?>
<form action="#">
<input type="submit" name="submit" value="submit" style="position:fixed;bottom:0px;left:0px;width:100%;" />
</form>
2. Using Javascript.Javascript is client-side
.It doesnt reload the page.
<script>
function writeName()
{
document.write="Kai Jim Refsnes";
}
</script>
<button onclick="writeName();">submit</button>
3. Using AJAX.With AJAX you can combine both PHP and Javascript.For this simply print a message AJAX will be too much but for larger/complex data transfers between server and client without reloading AJAX is much helpful.
AJAX refrences: http://api.jquery.com/jQuery.ajax/ ; http://www.w3schools.com/ajax/
Upvotes: 0
Reputation: 22592
You can't call a PHP function from JavaScript.
PHP is interpreted on the server side and JavaScript on the client side.
You could use an AJAX request or you could write a JavaScript function at runtime with the PHP
Something like:
echo <<<END
<form>
<input type='button' onClick='function writeName() { document.write("{$php_var_name}") }' style='position:fixed;bottom:0px;left:0px;width:100%;'>
</form>
END
Upvotes: 1
Reputation: 796
PHP is run on the server side, so you should use AJAX, which allows you to run PHP after a page has already loaded.
AJAX is asynchronous javascript - you basically use Javascript to query a PHP page on your server, and you receive a response that you then can print to your page.
Upvotes: 0