I am working in wordpress and I want to fetch the updated value of aid field from form each time a submit button is pressed. There are two submit buttons and I want the id as per the clicked row
HTML Form(it is shown dynamically with php code)
foreach( $results as $result ) {
$form.= '<form id="voteform" action="" method="post">';
$form.= "<input id='aid' name='aid' type='text' value='$result->aid'>";
$form.=" <input class='star' class='star' id='star5' type='submit' name='star5' value='5'>";
$form.=" <input class='star' class='star' id='star6' type='submit' name='star5' value='5'></form";
jQuery
$(document).on("click",".star", function(e) {
e.preventDefault();
var aidd = jQuery("#aid").val();
sentdata =({
action: 'star',
aid:aidd,
})
$.post(yes.ajaxurl, sentdata, function (res) { //start of funciton
alert(aid);
$("#myresult").html(res);
return false;
} //end of function
,
'json'); }); //end inner function
}); //end main function
php code
add_action( 'wp_ajax_star', 'star' );
add_action( 'wp_ajax_nopriv_star', 'star');
function star()
{
$aid = $_POST['aid'];
echo json_encode($aid);
die();
}
So you have to get the closest parent form element for the submit button then.
Try like this:
var aidd = $(this).closest("form").find("#aid").val();
Related
I am having issue after a successful AJAX post, where the updated div disappears after a few moments
Below are the jquery/PHP/POST data in succession.
Button On Click Function:
function Delete_ID(clickBtnValue,clickBtnID,clickBtnName) {
var my_data = {"passvalue": clickBtnValue, "passid":clickBtnID, "passname":clickBtnName};
$.ajax({
type: 'POST',
url: '../Programs/Programs.php',
data: my_data,
success: function (data) {
$('#ProgramsTable').load("../Programs/ProgramChange.php");
$('#update-div').html(data);
}
});
}
PHP DIV display:
$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
$html = '<br><div id="ProgramsTable"><div class="TABLE">';
for ($ii=0; $ii < count($list_programs); $ii++) {
$html .= <<<HTML
<div class="CELL">
<form method="post" action>{$list_programs[$ii]["Program_Name"]}
<button onclick="Delete_ID('Delete','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" class="button">Delete</button>
<button onclick="Delete_ID('Edit','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" class="button">Edit</button>
</form>
</div>
HTML;
}
}
echo $html;
echo "</div></div><div id='update-div'></div>";
POST in Programs.php:
if (!empty($_POST)) {
if ($_POST['passvalue'] == "Delete"){
DB_Delete_Program_list($_POST['passid']);
echo $_POST['passname'] . " has been deleted";
}
if ($_POST['passvalue'] == "Edit"){
echo ' <div class="form_div"><form class="Edit_form" method="post">';
echo ' <div style="margin-top:5px"><input type="text" style="height:20px;" id="'.$_POST['passid'].'" value="'.$_POST['passname'].'" size="40" maxlength="253"></div>';
echo ' <div style="margin-top:10px"></div>';
echo ' <div ><input class="form_submit" type="Submit" name="Edit_button"></div>';
echo ' </form></div>';
}
return true;
}
When I press delete, it will display for example "Program 1 has been deleted" and then disappear
When I press edit, the new form table and display and then disappear
Here is a screen record of my issue
What do I need to change, to make it so my div data "table" refreshes with the latest SQL data while also keeping the success text message?
DSICLAIMER
Yes I am aware that the EDIT POST option is not how it's supposed to be, as I am just testing the success message return.
Yes there is SQL mitigation in place
I believe what's happening is when you click your button, you're submitting the form while also triggering your Delete_ID function. So, what happens is the JS function executes and displays your div, but the page also reloads, so you only see it for a moment. What you need to do is to call preventDefault() on the event that is generated by the onclick event.
As a tangent, to make passing the data to your Delete_ID function easier, I'd recommend using data attributes rather than passing the data as properties to the function itself.
This is how I'd redo your code.
For your form buttons, remove the onclick attribute, and use the data- attributes for relevant properties. I also added delete-button and edit-button classes to each button to distinguish them.
$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
$html = '<br><div id="ProgramsTable"><div class="TABLE">';
for ($ii=0; $ii < count($list_programs); $ii++) {
$html .= <<<HTML
<div class="CELL">
<form method="post" action>{$list_programs[$ii]["Program_Name"]}
<button data-name-hash="{$list_programs[$ii]["Name_Hash"]}" data-program-name="{$list_programs[$ii]["Program_Name"]}" class="button delete-button">Delete</button>
<button data-name-hash="{$list_programs[$ii]["Name_Hash"]}" data-program-name="{$list_programs[$ii]["Program_Name"]}" class="button edit-button">Edit</button>
</form>
</div>
HTML;
}
}
echo $html;
echo "</div></div><div id='update-div'></div>";
Then in your javascript, assign the on-click function to buttons with the matching class. This allows you to access the click event in that function.
$('.delete-button').click(Delete_ID);
Now, update the function definition to use the click event and pull the data from data attributes:
function Delete_ID(event) {
event.preventDefault(); // Stop the form from submitting so the page doesn't reload
const clickedBtn = event.target; // This is a reference to the <button> itself.
const clickBtnValue = 'Delete'; // You could pass this via data attributes too; I assume you'll probably have a separate Edit_ID function though.
// Pull the values from the `data-` attributes on the clicked button
// Note that JS converts the kebab-case attribute names (eg: data-name-hash) to camelCase with "data" removed (eg: nameHash).
const clickBtnID = clickedBtn.dataset.nameHash;
const clickBtnName = clickedBtn.dataset.programName;
var my_data = {"passvalue": clickBtnValue, "passid":clickBtnID, "passname":clickBtnName};
$.ajax({
type: 'POST',
url: '../Programs/Programs.php',
data: my_data,
success: function (data) {
$('#ProgramsTable').load("../Programs/ProgramChange.php");
$('#update-div').html(data);
}
});
}
Here's a very basic JSFiddle example of using preventDefault with data attributes.
you need to prevent your form to be submitted when you press Delete/Edit button, you can do it by remove form tag
$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
$html = '<br><div id="ProgramsTable"><div class="TABLE">';
for ($ii=0; $ii < count($list_programs); $ii++) {
$html .= <<<HTML
<div class="CELL">
{$list_programs[$ii]["Program_Name"]}
<button onclick="Delete_ID('Delete','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" class="button">Delete</button>
<button onclick="Delete_ID('Edit','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}')" class="button">Edit</button>
</div>
HTML;
}
}
echo $html;
echo "</div></div><div id='update-div'></div>";
or return false on button click event
$list_programs = DB_Get_Program_List();
if (!is_null($list_programs)) {
$html = '<br><div id="ProgramsTable"><div class="TABLE">';
for ($ii=0; $ii < count($list_programs); $ii++) {
$html .= <<<HTML
<div class="CELL">
<form method="post" action>{$list_programs[$ii]["Program_Name"]}
<button onclick="Delete_ID('Delete','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}'); return !1" class="button">Delete</button>
<button onclick="Delete_ID('Edit','{$list_programs[$ii]["Name_Hash"]}', '{$list_programs[$ii]["Program_Name"]}'); return !1" class="button">Edit</button>
</form>
</div>
HTML;
}
}
echo $html;
echo "</div></div><div id='update-div'></div>";
I have a block of code which is a dynamically generated div with a form (based on array loop) that has dynamic inputs which are added by a button:
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<?php endforeach;?>
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $('#tickerID').val();
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
That code above is working and simply allows the '+' button to add a new input. I'm getting the input values as well as the tickerID from my hidden input in preparation for ajax submission. I'm getting what I expect from the serialized form but I have an issue.
The following code:
<script type="text/javascript">
$("#Items").submit(function(e) {
e.preventDefault();
var data = $("#Items").serialize();
console.log(data);
});
</script>
Prints this:
Items%5B%5D=this&Items%5B%5D=is&Items%5B%5D=test&tickerID=1
Which I expect. The problem is that with my ajax call to my mysql insert function, I need to insert one record for each value plus the tickerID. My sql insert is inserting into columns tickerID and content. So for the above console.log, I would need the following insert:
tickerID | content
----------------------
1 this
1 is
1 test
How can I properly pass my form data to the ajax and then do something like a foreach in order to insert multiple records?
ajax call
<script type="text/javascript">
$("#Items").submit(function(e) {
$.ajax({
type: "POST",
url: addticker.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
addticker.php
$tickerID = $_POST[''];
$content = $_POST[''];
$addTicker = "
INSERT INTO tickerTable (tickerID, content)
values ('$tickerID', '$content');
"
$mysqlConn->query($addTicker)
Hope this works.
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
foreach ($items as $item){
$addTicker = "
INSERT INTO tickerTable (tickerID, content)
values ('$tickerID', '$item');
"
$mysqlConn->query($addTicker);
}
I have a formA that posts and saves to the MYSQL DB
<form name="A" id="FormA" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <== first visable form ,Submitting the data into DB
........field inputs. .....
<input type="submit" class="btn btn-primary" value="Submit">
</form>
I have a hidden form called PayForm that store some var with hidden input method and get the $input_amount as amount from FromA
It is noted that I haven't made the submit button .
This form is going to post to the EPayment Gateway .
<form name="payForm" id="payForm" method="post" action=" https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp">
<input type="hidden" id="merchantId" value="sth">
<input type="hidden" id="amount" value="<?php echo $input_amount; ?>" >
<input type="hidden" id="orderRef" value="<?php date_default_timezone_set("Asia/Taipei"); $date = date('m/d/Y h:i:s a', time()); echo $date ; ?>">
<input type="hidden" id="currCode" value="sth" >
<input type="hidden" id="mpsMode" value="sth" >
<input type="hidden" id="successUrl" value="http://www.yourdomain.com/Success.html">
<input type="hidden" id="failUrl" value="http://www.yourdomain.com/Fail.html">
<input type="hidden" id="cancelUrl" value="http://www.yourdomain.com/Cancel.html">
...
</form>
Here is my idea workflow :
1)User press "Submit" button in FormA ==> info in FormA is going to store into DB .
2)JS is running . Force the PayForm to post automatically . Then, The user is directed to the Payment Gateway .
In short , the Submit button in FormA trigger both forms post
actions .
Here is my JS
<script type='text/javascript'>
var payFormDone = false;
$('#FormA').on('submit', function(e){
if( !payFormDone ) {
e.preventDefault(); // THIS WILL TRIGGER THE NEXT CODE
$('#payForm').submit();
}
});
$("#payForm").submit(function(event) {
/* stop form from submitting normally */
//event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr( 'action' );
/* Send the data using post with element id name and name2*/
var posting = $.post( url, {
merchantId: $('#merchantId').val(),
amount: $('#amount').val(),
orderRef: $('#orderRef').val(),
currCode: $('#currCode').val(),
mpsMode: $('#mpsMode').val(),
successUrl: $('#successUrl').val(),
failUrl: $('#failUrl').val(),
cancelUrl: $('#cancelUrl').val(),
payType: $('#payType').val(),
lang: $('#lang').val(),
payMethod: $('#payMethod').val(),
secureHash: $('#secureHash').val()
} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
payFormDone = true;
$('#FormA').submit();
});
});
</script>
Now ,the idea is not working . It can only trigger second form action .
The first form action is not triggered .At least ,the data in FormA has not saved to the DB .
In short ,
posting.done(function( data ) {
alert('success');
payFormDone = true;
$('#payFormCcard').submit();
});
Is not working .I think !
update
This is how I post FormA to the server
<?php
// Include config file
require_once 'database.php';
header("Content-Type:text/html; charset=big5");
print_r($_POST);
// Define variables and initialize with empty values
$CName = $Address = $Phone = $amount= $Purpose= $Ticket = "";
$CName_err = $Address_err = $Phone_err = $amount_err = $Purpose_err = $Ticket_err="";
// Processing form data when form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate name
$input_CName = trim($_POST["CName"]);
if (empty($input_CName)) {
$CName_err = "Please enter a name.";
} elseif (!filter_var(trim($_POST["CName"]), FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => "/^[a-zA-Z'-.\s ]+$/")))) {
$CName_err = 'Please enter a valid name.';
} else {
$CName = $input_CName;
}
......
if (empty($CName_err) && empty($Address_err) && empty($amount_err) && empty($Phone_err)) {
// Prepare an insert statement
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO donation (CName, Address, Phone, Amount ,Ticket, Purpose) VALUES (?, ?, ?, ? ,?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($CName, $Address, $Phone, $amount ,$Ticket ,$Purpose));
Database::disconnect();
}
}
?>
you should not comment event.preventDefault(); from the second form. Currently what happens is it submitting it as default action which is post to url.
Inside posting.done() please remove/detach the onSubmit handler for FormA just before calling the $('#FormA').submit();
posting.done(function( data ) {
alert('success');
$('#FormA').off('submit');
$('#FormA').submit();
});
EDIT:
Okay, why not send the formA fields with AJAX inside its onSubmit handler and submit formB from the posting.done() handler ?
<script type='text/javascript'>
$('#formA').on('submit', function(e){
e.preventDefault();
/* Send the data using post with element id name and name2*/
var posting = $.post( "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>", {
field1: $('#field1').val(),
.....
} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
$('#FormB').submit();
}
});
</script>
The submit handler for FormA actually prevents the submission of the form. That's why data is not saved to db.
$('#FormA').on('submit', function(e){
if( !payFormDone ) {
e.preventDefault(); // => HERE you are preventing the form from submitting
$('#payForm').submit();
}
});
Here you are in the submit handler for the form, but the call to preventDefault stops the submit for FormA and instead triggers the submit of payForm.
See https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Also instead of having that you trigger via javascript I'd probably send the first one normally. Then as response of the POST in the first form You might print a message to the user with something like: "You are being redirected to the payment gateway.. " and an hidden form with all the fields that is triggered automatically after x seconds. IMHO this approach is easier and more reliable.
So in the first html page I'll remove all your javascript code and leave only:
<form name="A" id="FormA" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
........field inputs. .....
<input type="submit" class="btn btn-primary" value="Submit">
</form>
When the user clicks on the button he submits the data to the php page in POST. On the server the data is saved to DB and the server prints a message to the user and redirect to the payment gateway (via javascript this time). Something like:
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') {
.... save data to db
?>
<form name="payForm" id="payForm" method="post" action=" https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp">
<input type="hidden" id="merchantId" value="sth">
<input type="hidden" id="amount" value="<?php echo $input_amount; ?>" >
<input type="hidden" id="orderRef" value="<?php date_default_timezone_set("Asia/Taipei"); $date = date('m/d/Y h:i:s a', time()); echo $date ; ?>">
<input type="hidden" id="currCode" value="sth" >
<input type="hidden" id="mpsMode" value="sth" >
<input type="hidden" id="successUrl" value="http://www.yourdomain.com/Success.html">
<input type="hidden" id="failUrl" value="http://www.yourdomain.com/Fail.html">
<input type="hidden" id="cancelUrl" value="http://www.yourdomain.com/Cancel.html">
<p>You are being redirected to the payment gateway. If the redirect takes too long</p>
<input type="submit" value"click here">
</form>
<script>
// submits the form after 5 seconds
setTimeout(function(){ $('#payForm').submit(); }, 5000);
</script>
<?php } // this ends the POST block ?>
If I correctly understand the question:
<script type='text/javascript'>
$('#FormA').on('submit', function(e){
e.preventDefault();
$('input[type="submit"]', $(this)).attr('disabled','disabled');
$.post( $(this).attr('action'), $(this).serialize(), function() {
var $payForm = $("#payForm");
$.post( $payForm.attr('action'), $payForm.serialize(), function(data) {
alert('success');
// redirect to whereever you want
});
});
});
</script>
UPDATE:
case 2) redirecting to payment gateway:
<script type='text/javascript'>
$("#payForm").submit(function(e) {
alert('redirecting to payment gateway');
});
$('#FormA').on('submit', function(e){
e.preventDefault();
$('input[type="submit"]', $(this)).attr('disabled','disabled');
$.post( $(this).attr('action'), $(this).serialize(), function() {
$("#payForm").submit();
});
});
</script>
NOTE: replace all your script with just this one, and check in browser if requests are made in the data posted - F12 (Developer tools) - Network tab.
Keep in mind that this code is written on a scratch so it may have some errors, but it shows the way.
I am working on POS web.
creating form for each item in cart/order i.e multiple forms in loop and giving them unique ids ('id'=>'cart_'.$line )(cart_1,cart_2).
and created an update link in loop for each form. code below
echo form_open($controller_name."/edit_item/$line", array('class'=>'form-horizontal', 'id'=>'cart_'.$line));
echo form_input(array('name'=>'quantity','value'=>$item['quantity'],'size'=>'2', 'id'=>'quantity','class'=>'form-control'));
echo form_input(array('name'=>'discount','value'=>$item['discount'],'size'=>'3', 'id'=>'discount', 'class'=>'form-control'));?>
<a href="javascript:document.getElementById('<?php echo 'cart_'.$line ?>').submit();" id="anchor" title=<?php echo $this->lang->line('sales_update')?> >
This fulfils the update requiremnt like when I update a quantity and click the link it updates the price.
But now the problem is that I want my form to submit on onChange event of quantity field.
1) First Try
<script type="text/javascript">
$("#quantity,#discount").on('change',function(){
var quantity=$("#quantity").val();
var discount=$("#discount").val();
if(quantity!=""&&discount!=""){
document.getElementById('anchor').click();
console.log('form send');
}
});
</script>
this is what I tired but it only works if there is only one item in order
2)Second try
function updateQuantity(anchorID){
if(anchorID != ""){
document.getElementById(anchorID).click();
}
}
echo form_input(array('name'=>'quantity','value'=>$item['quantity'],'size'=>'2', 'onChange'=>'updateQuantity(HERE I WANT TO PASS "anchorID_LOOP VALUE")' 'id'=>'quantity','class'=>'form-control'));
<a href="javascript:document.getElementById('<?php echo 'cart_'.$line ?>').submit();" id='<?php echo 'anchorID_'.$line ?>' title=<?php echo $this->lang->line('sales_update')?> >
Rather than triggering a button.click() You should try the following:
echo form_open($controller_name."/edit_item/$line", array('class'=>'form-horizontal line-item', 'id'=>'cart_'.$line));
echo form_input(array('name'=>'quantity','value'=>$item['quantity'],'size'=>'2', 'id'=>'quantity','class'=>'form-control cartline', 'data-form' => $line));
echo form_input(array('name'=>'discount','value'=>$item['discount'],'size'=>'3', 'id'=>'discount', 'class'=>'form-control cartline', 'data-form' => $line));?>
<a href="javascript:document.getElementById('<?php echo 'cart_'.$line ?>').submit();" id="anchor" title=<?php echo $this->lang->line('sales_update')?> >
Notice I gave the form control an extra class and a data- attribute to hold the $line variable
So now I can catch the event and submit the form
$(function(){
$('.cartline').change(function(){
var line = $(this).attr('data-form');
$('#cart_' + line).submit();
});
});
To send the form via AJAX, you have to handle the form submit function (I gave the form a new class line-item)
$(".line-item").submit(function(event) {
event.preventDefault();
var line_form = $( this ),
url = line_form.attr( 'action' );
//Make your data
$.post( url, { data-field1: $('text1').val(), data-field1: $('text2').val() }, function(data){
alert('Form Posted')
});
});
I'm trying stop multiple submit buttons.I'm new to php and javascript.I did try lot of different options of stack overflow answers.I did check session token but it is not working for me because i'm submitting the form from JavaScript.You can see the code to disabled button . When i click the button it is disabled and form submited but it is not reaching the btn-paid code of php. Please help.
php code1:
<?php
include('sessionstart.php');
include('session.php');
include('processtransaction.php');
?>
<script src="js/mytransaction.js"></script>
php code1 will call the javascript and javascript has the form submit. If the form is submitted then it disable/(session token process) the button paid and it should call the code of btn-paid.
javascript code mytransaction:
$(document).ready(function() {
var table = $('#myTransactionitems').dataTable(); //Initialize the datatable
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'transactions',
dataType: 'json',
success: function(s){
console.log(s);
table.fnClearTable();
for(var i = 0; i < s.length; i++) {
var disp1 = '';
if (s[i][4] != 'Reserved') {
disp1 = 'display:none;'
}
table.fnAddData([
"<form method='post' action='reservationdetails'><input name = 'transactionid' type='hidden'\
value='"+s[i][0]+"'></input><input type='submit' id = 'btn-bank' name='btn-bank' value = '"+s[i][0]+"' class='btn btn-link'>\
</input></form>",
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
"<form method='post'><input name = 'transactionid' type='hidden'\
value='"+s[i][0]+"'><input name = 'donationid' type='hidden'\
value='"+s[i][2]+"'><input name = 'splitamount' type='hidden'\
value='"+s[i][3]+"'></input></input><input type='submit' id = 'btn-paid' name='btn-paid' value = 'Paid' onclick='this.disabled=true;this.form.submit();' style='" + disp1 +"' class='btn btn-sm btn-success pull-left '>\
</input></form><form method='post'><input name = 'transactionid' type='hidden'\
value='"+s[i][0]+"'><input name = 'donationid' type='hidden' \
value='"+s[i][2]+"'><input name = 'splitamount' type='hidden'\
value='"+s[i][3]+"'></input><input type='submit' id = 'btn-cancel' name='btn-cancel' value = 'Cancel' onclick='this.disabled=true;this.form.submit();' style='" + disp1 +"' class='btn btn-sm btn-danger pull-right'>\
</input></form>"
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
php code2 processtransaction:
<?php
if (isset($_POST['btn-paid'])) {
require_once("dbcontroller.php");
$db_handle = new DBController();
$conn = $db_handle->connectDB();
$query = "update MYTRANSACTION set STATUS =? where DONATION_ID=? AND ID=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("sii",$status,$donation_id, $transaction_id);
$stmt->execute();
$stmt->close();
$db_handle->closeDB($conn);
}
?>
If you want to prevent the user from clicking twice before page ends loading (causing 2 posts), it would better to use javascript. As you are already using jQuery, you can do the following:
$("input[type='submit']").click(function(e) {
e.preventDefault(); // Prevent the page from submitting on click.
$(this).attr('disabled', true); // Disable this input.
$(this).parent("form").submit(); // Submit the form it is in.
});
Edit:
To cater for someone immediately submitting before page loads completely (ie before JS loads), you can make the following changes.
In your HTML form, add disabled to your submit button:
<input type="submit" value="Submit" disabled />
And change your JS to the following:
$("input[type='submit']").attr('disabled', false); // Enable this input.
$("input[type='submit']").click(function(e) {
e.preventDefault(); // Prevent the page from submitting on click.
$(this).attr('disabled', true); // Disable this input.
$(this).parent("form").submit(); // Submit the form it is in.
});
What this does is makes the submit button disabled until JS has loaded. Once JS loads, it will enable the submit button and then remaining things will work as before.