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.
Related
I am building a comment system in which there is features like: delete main post, delete comment, delete reply, edit main post, edit comment, edit reply, Read more/Read less for post that is >250 character. So i am now at the stage of making the edit for reply post to a comment, everything else is working perfectly except this one, when i click i need to see reply post with Read More/Read Less feature, so to make this happen after ajax response i needed to paste the javascript codes for this feature in the php script which edit the reply, so when i make .html(data) i see the javascript codes inside the span which i want the response to be shown ! please help ! i made the same script for comment and same way placing javascript code in the php page that edited the comment but i do not see the javascript lines ! below are pictures that shows what is happening and my script next :
// THIS TAKES CARE OF THE EDIT FEATURE OF THE REPLY ON BOARD_COMMENT PAGE
$(document).on("click", ".board_reply_edit_button", function() {
// this will select the form in which is contained the edit button
var editBoardButtonAttribute = $(this).attr("id");
var editBoardButtonIdArray = editBoardButtonAttribute.split("-");
var editBoardButtonId = editBoardButtonIdArray[0];
$("#"+editBoardButtonId+"-formBoardReplyEdit").toggle();
$("#"+editBoardButtonId+"-spanBoardReplyEdit").toggle();
// if the cancel button is clicked, this happens
$(document).on("click", ".board_cancel_button", function() {
// this will select the form in which is contained the edit button
var cancelBoardAttribute = $(this).attr("id");
var cancelBoardButtonIdArray = cancelBoardAttribute.split("-");
var cancelBoardButtonId = cancelBoardButtonIdArray[0];
$("#"+cancelBoardButtonId+"-formBoardReplyEdit").hide();
$("#"+cancelBoardButtonId+"-spanBoardReplyEdit").show();
});
// if the edit button is clicked we send this ajax call
$(document).on("click", ".board_edit_save_button", function(e) {
e.preventDefault();
// this will select the form in which is contained the edit button
var saveBoardAttribute = $(this).attr("id");
var saveBoardButtonIdArray = saveBoardAttribute.split("-");
var saveBoardButtonId = saveBoardButtonIdArray[0];
var editBoardTextareaVal = $("#"+saveBoardButtonId+"-textareaBoardReplyEdit").val();
url = "widgets/edit_board_comment_reply.php";
if (editBoardTextareaVal === "") {
CustomSending("This post can't be left blank")
setTimeout(function () {
$("#sending_box").fadeOut("Slow");
$("#dialogoverlay").fadeOut("Slow");
}, 2000);
// this makes the scroll feature comes back
setTimeout(function(){
$("body").css("overflow", "auto");
}, 2001);
} else {
$.ajax({
url: url,
method: "POST",
data: {
reply_id: saveBoardButtonId,
board_reply_textarea: editBoardTextareaVal
},
beforeSend: function() {
CustomSending("Sending...");
},
success: function(data){
$("#sending_box").fadeOut("Slow");
$("#dialogoverlay").fadeOut("Slow");
// this makes the scroll feature comes back
$("body").css("overflow", "auto");
$("#"+saveBoardButtonId+"-spanBoardReplyEdit").html(data); //// THIS IS THE KEY LINE
$("#"+saveBoardButtonId+"-formBoardReplyEdit").hide();
$("#"+saveBoardButtonId+"-spanBoardReplyEdit").show();
}
});
}
});
});
this is the edit_board_comment_reply.php file :
<?php
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
if(isset($_POST['reply_id'], $_POST['board_reply_textarea'])) {
$reply_id = (int)$_POST['reply_id'];
$board_reply_textarea = mysql_prep($_POST['board_reply_textarea']);
// INSERT into table
$query = "UPDATE board_comment_reply_table ";
$query .= "SET reply = '$board_reply_textarea' ";
$query .= "WHERE reply_id = $reply_id";
$result = mysqli_query($connection, $query);
// now we select the updated board post
$query2 = "SELECT * FROM board_comment_reply_table ";
$query2 .= "WHERE reply_id = $reply_id ";
$result2 = mysqli_query($connection, $query2);
confirm_query($result2);
$result_array = mysqli_fetch_assoc($result2);
}
echo nl2br($result_array['reply']);
?>
<script>
// This takes care of the board comment Continue Reading feature ---------------------------------------------------------
$(".reply_content_span").each(function(){
var boardReplyPostThis = $(this);
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if(boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
boardReplyPostThis.text(boardPostTextCut+"...");
boardReplyPostThis.append('<a class="board_read_more_link board_reply_read_more" id="'+boardPostId+'-readMoreComment">Read More</a>');
} else {
boardReplyPostThis.text(boardPostText);
}
$("body").on("click", ".board_reply_read_more", function(e){
e.preventDefault();
boardReplyPostThis.text(boardPostText);
boardReplyPostThis.append('<a class="board_read_more_link board_reply_read_less">Read Less</a>');
});
$("body").on("click", ".board_reply_read_less", function(e){
e.preventDefault();
boardReplyPostThis.text(boardPostTextCut+"...");
boardReplyPostThis.append('<a class="board_read_more_link board_reply_read_more">Read More</a>');
});
});
</script>
This is the html code :
<span class="comment_content_span" id="<?php echo $board_comment_id_number;?>-spanBoardCommentEdit"><?php echo nl2br($board_comment_text);?></span>
<form action="" method="post" class="board_comment_edit_form" id="<?php echo $board_comment_id_number;?>-formBoardCommentEdit">
<textarea rows="2" name="board_comment_edit_textarea" class="board_comment_edit_textarea" id="<?php echo $board_comment_id_number;?>-textareaBoardEdit"><?php echo $board_comment_text;?></textarea>
<input type="submit" value="Edit" class="board_edit_save_button" id="<?php echo $board_comment_id_number;?>-saveBoardCommentEdit"/>
<input type="button" value="Cancel" class="board_cancel_button" id="<?php echo $board_comment_id_number;?>-cancelBoardCommentEdit"/>
</form>
Solution found !
instead of the javascript between the script tags, I added this line in the edit_board_comment_reply.php
<script src="js/board.js"></script>
It seems that the appended javascript exitsts in "data" which is send back from your php script. First of all you should try to define the "dataType" property of your ajax-post because the output is preprocessed by jquery depending on that property.
After that you can try to grab just the content-division from your resonse-html and append that instead of the whole result.
For example like this $(body).append($(data).find('#contentID')).
I have a button, when pressed has to call a function from an external php file and load it in a new page.
When I click the "SHOW" button on my index.php page, it shows me the message hold in "mesaj", but displays it in index.php page (that I don`t want!).
What I want to accomplish is when I click on the "SHOW" button on my index.php it shows me the content of the message into another php page, named - for eg - content.php. I want to set the href.
index.php
<input type = "button" class="btn btn-primary" id = "show" onClick = "show()" value = "SHOW"/>
functions.php
function show()
{
database();
$sql = "SELECT title FROM `Articles`";
$titleSql = mysql_query( $sql ) or die("Could not select articles:");
$html = '<html><body><div class="container"><h2>Basic List Group</h2><ul class="list-group">';
while ($title = mysql_fetch_array($titleSql)) {
$html .= '<li class="list-group-item">'.$title["title"].'</li>';
}
$html .= '</ul></div></body></html>';
echo $html;
//die(json_encode(array("mesaj" => "Entered data successfully ")));
}
function.js
function show(){
var n = $('#show').val()
$.post("functions.php", {show:n}).done(function(mesaj){
//$(document).html(mesaj);
document.write(mesaj);
});
}
There is no reason (apparently) to go from PHP to JS in your case. You'd use JS $.post if you need a change of the DOM after it loaded. You can just do this:
<a href="function.php" class="btn btn-primary" id="show"/>SHOW</a>
This works without going thru JS.
If you want to use BUTTON and go via JS then do this:
<input type="button" class="btn btn-primary" id="show" value="SHOW"/>
jQuery:
$('#show').click(function(e){
e.preventDefault();
window.location.href = 'function.php';
});
Plain JS:
document.getElementById("show").onclick = function(){
window.location.href = 'function.php';
}
As a note, be careful because <button> if used inside a form when clicked submits the form. That's why the e.preventDefault();
Let's say you have multiple functions in your function.php and you need to call one a specific one, I would do this:
function.php
if(isset($_GET['fn1'])){
function functionOne(){
//do something
}
}
if(isset($_GET['fn2'])){
function functionTwo(){
//do something else
}
}
And call it this way:
<a href="function.php?fn1" class="btn btn-primary" id="show"/>SHOW</a>
or
$('#show').click(function(e){
e.preventDefault();
window.location.href = 'function.php?fn1';
//window.location.href = 'function.php?fn2';
});
I am using a custom mvc framework and have added a favourite button. Once pressed this displays a 'successfully added to favourites' div, when clicked again it displays a 'successfully removed from favourites' div.
My query works fine, adding and deleting from my favourite table as it should.
What I would like to do now is change the state of the button depending on the selection. For example, if the user has the book in their favourites add btn-success class, if the user hasn't, use the btn-default class.
I'm not sure the best way to approach this. I'm new to php and js so any advice or direction is appreciated. I have tried adding toggleClass to my JS but it's not working. Do I need to perform a query/check on pageLoad?
I have included my code below for reference.
itemView.php
echo
'<td>
<button id="fav" value="'.$book->id.'" type="button" class="btn btn-default"></button>
</td>';
JS (in itemView.php)
$(document).ready(function(){
$( "#fav" ).click(function(){
book_id = $(fav).val();
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>books/checkFav',
data: {book_id:book_id},
success: function () {
window.location.reload(true);
$("#fav").addClass( "btn-success" );
}//end success
});//end ajax
});
});
my checkFav function
public function checkFav($bookid,$userid)
{
$bookid=$_REQUEST['book_id'];
$userid=$_SESSION['user_id'];
$sql = "SELECT * FROM favourite WHERE book_id = :book_id AND user_id = :user_id";
$query = $this->db->prepare($sql);
$query->bindParam(':user_id', $userid);
$query->bindParam(':book_id', $bookid);
$query->execute();
$rows_found = $query->fetchColumn();
if(empty($rows_found)) {
$sql = "INSERT INTO favourite (book_id, user_id) VALUES (:book_id, :user_id)";
$query = $this->db->prepare($sql);
$query->bindParam(':user_id', $userid);
$query->bindParam(':book_id', $bookid);
$query->execute();
if ($query->rowCount() == 1) {
// successful add to favs
$_SESSION["feedback_positive"][] = FEEDBACK_ADDED_TO_FAVS;
return true;
}
} else {
$sql = "DELETE FROM favourite WHERE book_id = :book_id AND user_id = :user_id";
$query = $this->db->prepare($sql);
$query->bindParam(':user_id', $userid);
$query->bindParam(':book_id', $bookid);
$query->execute();
if ($query->rowCount() > 0) {
// successful remove from favs
$_SESSION["feedback_negative"][] = FEEDBACK_REMOVED_FROM_FAVS;
return true;
}
}
}
Use session variable in the ajax request script and using that session variable in page where button exist you can play with button css. for example:
Put this code where Button exists.
$css = "btn_default";
if($_SESSION['btnClicked'] == "success") {
$css = "btn_success";
}
Use $css variable in the button class like--
<button id="fav" value="'.$book->id.'" type="button" class="btn <?php echo $css?>"></button>
This session will manage in the ajax script where in you are adding and deleting favourite.
set session value
$_SESSION['btnClicked'] = 'success'
below the line
$_SESSION["feedback_positive"][] = FEEDBACK_ADDED_TO_FAVS;
and unset the session
unset($_SESSION['btnClicked']);
after the line.
$_SESSION["feedback_negative"][] = FEEDBACK_REMOVED_FROM_FAVS;
I have a javascript function that is triggered when a button is pressed. That function loads an external page with the values of a field.
My problem is that when I refresh the page my clicked button is reset. What I want is to keep that button value when it refreshes so it still loads that page and only reset when another button is pressed.
js code
<script>
$(function() {
$("button.btn").click(function() {
var tip = document.getElementById("tip5").value;
var id_local = document.getElementById("id_local").value;
$("#tipuri_rezervare").load("select_tip_rezervare.php?id=" + id_local + "&tip=" + tip);
});
});
</script>
php code
$stmt = $dbh->prepare("SELECT *
FROM Tip_Rezervare
INNER JOIN Local ON Local.ID_Local=:id_local
INNER JOIN Leg_Tip_Local ON Tip_Rezervare.ID_Tip=Leg_Tip_Local.ID_Tip and Leg_Tip_Local.ID_Local=:id_local");
$stmt->bindParam(':id_local', $id, PDO::PARAM_INT);
$stmt->execute() ;
while ($row = $stmt->fetch()) {
$local = $row['Denumire_Local'];
echo'<button type="button" class="btn btn-danger" id="tip'.$row['ID_Tip'].'" value="'.$row['ID_Tip'].'">'.$row['Nume'].'</button>';
}
?>
</div>
<form id="tip" method="post">
<input type="hidden" name="id_local" id="id_local" value="<?php echo $id;?>">
<div id="tipuri_rezervare"></div>
You need to make an Ajax call & set a session during the result fetch from external page but before page refresh and read the session values after page refreshed & set it on page.
I have tried instant search using jQuery. It is working fine until I click the search button. When I click the search button the page will reload and the results would disappear.
Here's my code:
search.php
<div id="search-container">
<form action="search.php" method="POST">
<input type="text" name="key" id="key" placeholder="search" onkeydown="searchIt();"></input>
<input type="submit" name="search" id="search" value="search"></input>
</form>
</div>
<div id="res-container"></div>
And the script is:
<script type="text/javascript">
function searchIt(){
var text = $("input[name='key']").val();
text = text.trim();
if(text.length>3){
$.post("query.php",{index: text}, function(data){
$("#res-container").html(data);
});
}
}
</script>
query.php
if(isset($_POST['index'])){
$key = mysqli_real_escape_string($con, $_POST['index']);
$key = trim($key);
$result = "";
if(!empty($key)){
$query = "SELECT * FROM users WHERE first_name LIKE '%$key%' OR last_name LIKE '%$key%'";
$query_run = mysqli_query($con, $query);
$row_count = mysqli_num_rows($query_run);
if($row_count == 0){
$result = "No results!!!";
}else{
while($query_row = mysqli_fetch_array($query_run)){
$fname = $query_row['first_name'];
$lname = $query_row['last_name'];
$name = $fname.' '.$lname;
$mail = $query_row['email_id'];
$id = $query_row['emp_id'];
$result .="<div class=\"qitems\"><div class=\"name\">$name</div><div class=\"mail\">$mail</div></div>";
}
}
}else{
$result = 'please enter a word';
}
}
echo ($result);
Until this everthing is working fine, but when I try to click search button the results would disappear.
I tried adding this in the script:
$(document).ready(function(){
$("input[name='search']").click(searchIt());
});
But there is no change. Please help me with this.
This should work:
$(document).ready(function(){
$('body').on('click', 'input[name="search"]', function(event)
{
event.preventDefault(); // This is important, since you are interacting with a valid html form/element
searchIt();
});
});
Update:
I've made a codepen for you. Look at it, it works perfectly fine:
http://codepen.io/dschu/pen/VmRJPZ
The reason is button of type "submit" effectively submits the page to form URL, which is the same page, thus has the same effect, as reloading, - here is your "reset" behaviour. Besides solution above you can also change input type from submit to button, which will avoid submitting the form (and manually preventing the event).