Reputation: 141
There already are some entries about the topic explaining that the only way is by using Ajax. However, I do not find solution for this problem: I just want that, once pressing a button in an HTML file, run a PHP function.
Imagine I have two buttons button1
button2
so I want each of them to run function run1()
function run2()
of my PHP file.
How the Ajax would look like? This is what I have.
HTML:
<script> // For button1
$(document).ready(function(){
$("#button1").click(function(){
var value = $("#button1").val();
$.ajax({
url: 'myPHP.php',
type: 'POST',
data: {button:value},
success: function(response){
$('#output').append(response);
}//end success
}); //end ajax
});
});
</script>
<body>
<form method="post" action="myPHP.php">
<button id= "button1" type="submit" value="value1">Button One</button>
<button id= "button2" type="submit" value="value2">Button Two</button>
</form>
</body>
PHP:
if($_POST['button'] == 'value1'){
// run function1;
}else{
// run function2;
}
Upvotes: 0
Views: 698
Reputation: 2302
Send the page the value via ajax, then use it within that page
$(document).ready(function(){
$("#button1").click(function(){ // the #id you supplied to the button, id= 'button1'
var value = $("#button1").val(); // Value of the button, value= 'button1value'
$.ajax({
url: 'phppage.php', // The php page with the functions
type: 'POST',
data: {button:value}, // the name you're assigning, think how a $_GET works in URL, .php?name=value...
success: function(response){
$('#output').append(response);
}//end success
}); //end ajax
});
});
php page
if($_POST['button'] == 'button1value'){ / $_POST['name of input/button'] == 'value being sent through'
// run function 1;
}else{
// run function2;
}
?>
This post, first answer, also answers depending how you intend to use it: using jquery $.ajax to call a PHP function
Upvotes: 1