2
I want to know how I can run a php function with the onclick event on an element a
, taking as an example:
<a href="">Teste onclick</a>
And the function:
function testeOnclick() {
echo 'Bem vindo ao SOpt';
}
2
I want to know how I can run a php function with the onclick event on an element a
, taking as an example:
<a href="">Teste onclick</a>
And the function:
function testeOnclick() {
echo 'Bem vindo ao SOpt';
}
6
What you can do is this:
<a href="pagina.php?id=1">Teste onclick</a>
Ai in PHP do so:
<?php
if(isset($_GET['id']) == 1){
testeOnclick();
}
?>
It would be a simple way to do it, but searching for Json/Ajax with PHP does it but in a way that you don’t need to refresh the page.
Thanks for the reply, really it is a MUCH simpler way to do, worth updating the page! Anyway thanks. ;)
4
You will have to use Ajax. Assuming that the php file containing your function is called "meuajax.php", using jQuery, you can use:
function chamarPhpAjax() {
$.ajax({
url:'meuajax.php',
complete: function (response) {
alert(response.responseText);
},
error: function () {
alert('Erro');
}
});
return false;
}
So on your link:
<a href="" onclick="return chamarPhpAjax();">Teste onclick</a>
Your file "meuajax.php":
function testeOnclick() {
echo 'Bem vindo ao SOpt';
}
testeOnclick();
2
If possible, you should create the routine in Javascript, but if there is no other way, you should run the PHP function in two ways:
to) Creating a PHP file that runs the function, and when the person clicks, redirect to the file that executes the action and does what has 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']);
?>
Thank you for the reply!
Browser other questions tagged php html onclick
You are not signed in. Login or sign up in order to post.
Use ajax friend.
– Guilherme Nascimento
possible duplicate of How to run PHP file from Javascript function?
– Guilherme Nascimento
@Guilhermenascimento The question is really similar, but I don’t think it’s about to be closed as a duplicate. Given that my question is more direct (as it already has very objective answers as well) and could help both new users and someone who has a lesser knowledge in the subject, and who managed to solve my problem with the answers from here, and not from there.
– GWER
@GWER The duplicate does not invalidate your question, just links both questions, I personally think the answer of rray would rather solve your problem. :)
– Guilherme Nascimento