I want to know how to execute a php function with the onclick event on a a
element, for example:
<a href="">Teste onclick</a>
And the function:
function testeOnclick() {
echo 'Bem vindo ao SOpt';
}
I want to know how to execute a php function with the onclick event on a a
element, for example:
<a href="">Teste onclick</a>
And the function:
function testeOnclick() {
echo 'Bem vindo ao SOpt';
}
You will have to use Ajax. Assuming that the php file that contains your function is called "myajax.php" using jQuery, you can use:
function chamarPhpAjax() {
$.ajax({
url:'meuajax.php',
complete: function (response) {
alert(response.responseText);
},
error: function () {
alert('Erro');
}
});
return false;
}
Then on your link:
<a href="" onclick="return chamarPhpAjax();">Teste onclick</a>
Your "myajax.php" file:
function testeOnclick() {
echo 'Bem vindo ao SOpt';
}
testeOnclick();
What you can do is this:
<a href="pagina.php?id=1">Teste onclick</a>
Then in PHP do so:
<?php
if(isset($_GET['id']) == 1){
testeOnclick();
}
?>
It would be a simple way to do it, but search on Json / Ajax with PHP does this but in a way that does not need to refresh the page.
If possible, you should create the routine in JavaScript, but if you do not have it, you should run the PHP function in two ways:
a) Creating a PHP file that runs the function, and when the person clicks, redirect to the file that performs the action and does what needs to be done next.
b) Create a PHP file that calls functions using the call_user_func method and make an ajax request to access it, as in the following example:
JavaScript code (jQuery):
$(document).on('click', 'a', function(e){
$.post('execute.php', {fuction: 'helloWorld'}, function(response){
console.log(response);
});
});
PHP code:
<?php
// execute.php
function helloWorld(){
echo 'Olá Stackoverflow! :)';
}
call_user_func($_POST['function']);
?>