Handling Multiple Buttons With Same Ajax Call
Solution 1:
When looping with PHP, you should NEVER use any id
on elements. Use classes instead... Or some data attributes.
You were using unique ids by adding a number to them... Fine. But a class is more useful since you can add one event handler to a class... Instead of n
event handlers for element created by the PHP iterations. So it avoid useless code duplication and just make sens.
That is what I suggest you now. Modify your PHP loop so it will create that HTML: (I removed all that seemed useless)
<divclass="card"data-id="0"><divclass="PayBillResults"></div><!-- To show Ajax Response Message --><divclass="card-header"><h1>XXX</h1></div><divclass="card-body"><form><inputname="user"value="user"type="hidden"><inputname="id"value="9"type="hidden"><inputname="reciver"value="ppp"type="hidden"><inputname="amount"value="333.0"type="hidden"><inputname="tax"value="5.0"type="hidden"><inputname="comment"value="XXX"type="hidden"></form><div><div><buttonclass="btn btn-success pay"value="pay">Pay</button></div><div><buttonclass="btn btn-danger decline"value="decline">Decline</button></div><div><buttonclass="btn btn-warning hide"value="hide">Hide</button></div></div></div></div>
See the data-id="0"
? That is where you will have your form number using the PHP iteration counter.
Now here is the client-side script to use once (do not loop that):
$(document.ready(function(){
// Change the URL to use with Ajax on button clickvarAjaxUrl = "";
$(".pay").on("click",function(){
AjaxUrl = "php/pay.php";
$(this).closest(".card").find("form").submit();
});
$(".decline").on("click",function(){
AjaxUrl = "php/decline.php";
$(this).closest(".card").find("form").submit();
});
// Form submit handler
$("form").submit(function(e) {
e.preventDefault();
var card = $(this).closest(".card");
var formData = $(this).serialize();
formData.append("formNumber",card.data("id"));
$.ajax({
type: 'POST',
url: AjaxUrl,
data: formData
})
.done(function(response) {
var messageAlert = response.type;
var messageText = response.message;
var alertBox = '<div class="alert ' + messageAlert + '"style="margin-top:10px;"><d style="font-size:12px; ">' + messageText + '</d></div>';
card.find(".PayBillResult").html(alertBox);
card.delay(3000).fadeOut(2000);
})
});
}); // End ready
So on .pay
or .decline
button click, the URL to use with the Ajax request is changed accordingly.
(I don't know the use of the third button)
Then the .closest()
form submits. And from $(this)
, which is the <form>
, you can find all the related elements you need.
Notice that the form number that is submitting is added to the formData.
You'll retreive it with $_POST['formNumber']
.
Post a Comment for "Handling Multiple Buttons With Same Ajax Call"