Here is a simple PHP form with a button..
<form method="POST"> <div class="mb-3"> <button type='button' id ="btnnew1" class="btn btn-info" >submit</button> <p></p> </div> </form>
Here is the Jquery functions which executes a PHP file.
$(document).ready(function(){ $("#btnnew1").click(function(e){ if(!confirm('Are you sure?')){ e.preventDefault(); return false; } else{ $.ajax({ url: 'test.php', success: function(data) { $("p").text(data); } }); } }); });
And the test.php is as follows,
<?php echo 'Button1 clicked' ?>
My question is how to modify my test.php
if I have multiple buttons.
As an example,
<form method="POST"> <div class="mb-3"> <button type='button' id ="btnnew1" class="btn btn-info" >submit</button> <p></p> </div> <div class="mb-3"> <button type='button' id ="btnnew2" class="btn btn-info" >submit</button> <p></p> </div> <div class="mb-3"> <button type='button' id ="btnnew3" class="btn btn-info" >submit</button> <p></p> </div> </form>
Result should be,
If btnnew1 clicks--->echo("Button1 clicked); If btnnew2 clicks--->echo("Button2 clicked); If btnnew3 clicks--->echo("Button3 clicked);
Update:
What If I need to run three different php functions(no any pattern)?
Ex: If btnnew1 clicks---> sleep(5) echo("Button1 clicked); If btnnew2 clicks---> sleep(15) echo("Button2 clicked by user); If btnnew3 clicks---> sleep(35) echo("Button3 clicked by user);
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…
<input type="button" style="background-color: #3CBC8D;padding:3px;" class="button" name="fcn1" value="Update My Status"/> <input type="button" class="button" style="background-color: #3CBC8D;padding:3px;" name="fcn2" value="Update My Status" />
Then go to jquery and use as below, success function change as you wish. Here I have used an alert box…
$(document).ready(function(){ $('.button').click(function(){ if(!confirm('Are you sure?')){ e.preventDefault(); return false; } else{ var clickBtnValue = $(this).attr('name'); var fetchdata= 'testme.php', data = {'action': clickBtnValue}; $.post(fetchdata, data, function (response) { // Response div goes here. alert("Updated successfully -"+response); }); } }); });
Finally change your
testme.php
as follows,if (isset($_POST['action'])) { switch ($_POST['action']) { case 'fcn1': fcn1(); break; case 'fcn2': fcn2(); break; } } function fcn1() { echo 'Button1 clicked'; exit; } function fcn2() { sleep(5); echo 'Button2 clicked'; exit; }