Here is a simple PHP form with a button..
JavaScript
x
7
1
<form method="POST">
2
<div class="mb-3">
3
<button type='button' id ="btnnew1" class="btn btn-info" >submit</button>
4
<p></p>
5
</div>
6
</form>
7
Here is the Jquery functions which executes a PHP file.
JavaScript
1
18
18
1
$(document).ready(function(){
2
$("#btnnew1").click(function(e){
3
if(!confirm('Are you sure?')){
4
e.preventDefault();
5
return false;
6
}
7
else{
8
$.ajax({
9
url: 'test.php',
10
success: function(data) {
11
$("p").text(data);
12
}
13
});
14
15
}
16
});
17
});
18
And the test.php is as follows,
JavaScript
1
5
1
<?php
2
3
echo 'Button1 clicked'
4
?>
5
My question is how to modify my test.php
if I have multiple buttons.
As an example,
JavaScript
1
15
15
1
<form method="POST">
2
<div class="mb-3">
3
<button type='button' id ="btnnew1" class="btn btn-info" >submit</button>
4
<p></p>
5
</div>
6
<div class="mb-3">
7
<button type='button' id ="btnnew2" class="btn btn-info" >submit</button>
8
<p></p>
9
</div>
10
<div class="mb-3">
11
<button type='button' id ="btnnew3" class="btn btn-info" >submit</button>
12
<p></p>
13
</div>
14
</form>
15
Result should be,
JavaScript
1
4
1
If btnnew1 clicks--->echo("Button1 clicked);
2
If btnnew2 clicks--->echo("Button2 clicked);
3
If btnnew3 clicks--->echo("Button3 clicked);
4
Update:
What If I need to run three different php functions(no any pattern)?
JavaScript
1
12
12
1
Ex:
2
If btnnew1 clicks--->
3
sleep(5)
4
echo("Button1 clicked);
5
6
If btnnew2 clicks--->
7
sleep(15)
8
echo("Button2 clicked by user);
9
If btnnew3 clicks--->
10
sleep(35)
11
echo("Button3 clicked by user);
12
Advertisement
Answer
In here I am changing little bit your default settings. This will help you as I can understand. You can try as below,
1)Change your button into input type..I have added some inline CSS as well. If you don’t like you may neglect it…
JavaScript
1
5
1
<input type="button" style="background-color: #3CBC8D;padding:3px;" class="button" name="fcn1" value="Update My Status"/>
2
3
4
<input type="button" class="button" style="background-color: #3CBC8D;padding:3px;" name="fcn2" value="Update My Status" />
5
Then go to jquery and use as below, success function change as you wish. Here I have used an alert box…
JavaScript123231$(document).ready(function(){
2$('.button').click(function(){
3
4if(!confirm('Are you sure?')){
5e.preventDefault();
6return false;
7}
8else{
9var clickBtnValue = $(this).attr('name');
10var fetchdata= 'testme.php',
11data = {'action': clickBtnValue};
12$.post(fetchdata, data, function (response) {
13// Response div goes here.
14
15alert("Updated successfully -"+response);
16
17});
18}
19
20});
21
22});
23
Finally change your
testme.php
as follows,JavaScript123231if (isset($_POST['action'])) {
2switch ($_POST['action']) {
3case 'fcn1':
4fcn1();
5break;
6case 'fcn2':
7fcn2();
8break;
9}
10}
11
12function fcn1() {
13
14echo 'Button1 clicked';
15exit;
16}
17
18function fcn2() {
19sleep(5);
20echo 'Button2 clicked';
21exit;
22}
23