How to call a php script/function on a html button click
Just try this:
<button type="button">Click Me</button><p></p><script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $.ajax({ type: 'POST', url: 'script.php', success: function(data) { alert(data); $("p").text(data); } }); });});</script>
In script.php
<?php echo "You win"; ?>
Of course AJAX is the solution,
To perform an AJAX request (for easiness we can use jQuery library).
Step1.
Include jQuery library in your web page
a. you can download jQuery library from jquery.com and keep it locally.
b. or simply paste the following code,
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Step 2.
Call a javascript function on button click
<button type="button" onclick="foo()">Click Me</button>
Step 3.
and finally the function
function foo () { $.ajax({ url:"test.php", //the page containing php script type: "POST", //request type success:function(result){ alert(result); } }); }
it will make an AJAX request to test.php when ever you clicks the button and alert the response.
For example your code in test.php is,
<?php echo 'hello'; ?>
then it will alert "hello" when ever you clicks the button.
You can also use
$(document).ready(function() { //some even that will run ajax request - for example click on a button var uname = $('#username').val(); $.ajax({ type: 'POST', url: 'func.php', //this should be url to your PHP file dataType: 'html', data: {func: 'toptable', user_id: uname}, beforeSend: function() { $('#right').html('checking'); }, complete: function() {}, success: function(html) { $('#right').html(html); } }); });And your func.php: function toptable() { echo 'something happens in here'; }
Hope it helps somebody