I want to disable button after click for about 3 sec, I do that but I have a problem, on my web app it's working more than 10 users and I want to resolve that click button when someone click on that button it generate some sort of code, and when 2 users click in same time it generate same code two times.
It's server side web app.
Code bellow
#using (Html.BeginForm("GenerateCodes", "Index", FormMethod.Post))
{
<div class="box-header">
<div class="row">
<div class="col-md-3 text-right">
<button type="submit" id="ok" class="btn btn-primary btn-lg">Generate</button>
<script>
var fewSeconds = 5;
$('#ok').click(function () {
// Ajax request
var btn = $(this);
btn.prop('disabled', true);
setTimeout(function () {
btn.prop('disabled', false);
}, fewSeconds * 1000);
});
} </script>
</div>
</div>
</div>
Is it possible to do that with ajax and jQuery and should this pass to controller?
Related
I have a button which is supposed to trigger a modal with a contact form. Part of the show.bs.modal function is an AJAX call to my DB to get some file details which are then meant to be shown in the modal-body.
The problem is that the modal does indeed open, but with no modal-body content, which means that the JavaScript code to trigger to the AJAX call is not working. I do not see any network activity in the browser debug menu, no call to the PHP file, and even an alert on top of the JS code telling me that that a button was pressed is not triggered. It seems like the whole JS code is circumvented, yet the modal still shows.
The same code works in another project, anyone has any idea as to why this is happening?
Button:
<div class="card-footer bg-light text-center">
<button id="modal_btn" name="modal_btn" type="button" class="btn bg-teal-400" data-toggle="modal" data-target="#modal_contact_form" data-imgid="'.$row['image_id'].'" data-keyboard="true">
<span class="icon-ico-mail4"></span> Anfragen
</button>
</div>
Modal:
<!-- Contact form modal -->
<div id="modal_contact_form" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-teal-300">
<h3 class="modal-title">Kaufanfrage - Artikel #1234</h3>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Abbrechen</button>
<button type="submit" class="btn bg-teal-300">Nachricht Senden</button>
</div>
</form>
</div>
</div>
</div>
<!-- /contact form modal -->
JavaScript:
<script type="text/javascript">
// DISPLAY EDIT RECORD MODAL
$('#modal_contact_form').on('show.bs.modal', function (event) {
//var button = $(event.relatedTarget) // Button that triggered the modal
window.alert("button clicked.");
var imgid = $(event.relatedTarget).data('imgid') // Extract info from data-* attributes
var modal = $(this);
var dataString = 'action=contact&imgid=' + imgid;
$.ajax({
type: "POST",
url: "./assets/ajax/ajax_action.php",
data: dataString,
cache: false,
success: function (data) {
console.log(data);
modal.find('.modal-body').html(data);
},
error: function(err) {
console.log(err);
}
});
});
</script>
try this:
$(document).on('show.bs.modal','#modal_contact_form', function (event) {
// TODO ....
});
Or you can use the onclick button trigger instead of modal show trigger
$("#modal_btn").click(function(event){
// TODO ...
});
Try This
const bsModal = document.querySelector('#exampleModal');
$(bsModal).on('shown.bs.modal', function() {
// YOUR CODE HERE....
})
I have a page where I have to fill the student details for example name, email and department. Once I fill the details and click the submit my button it goes to next page and it shows the entered student details in the next page.
Here I have shown the code step by step.
The below code after entering the details and clicking the submit button.
<div class="top-space-20">
<input class="btn btn-info" type="button" onclick="submitEvent()" class="btn" value="submit my details">
</div>
This is the script code for clicking the submit my details button.
function submitEvent() {
form = document.createElement("form");
form.method = "POST";
form.action = "/confirmation";
}
Once I clicked the button it goes to backend and fetch some details and it displays the confirmation.html page.
#app.route("/confirm",methods=['GET','POST'])
def confirm():
"Confirming the event message"
response_value = request.args['value']
return render_template("confirmation.html", value=json.loads(response_value))
#app.route("/confirmation", methods=['GET', 'POST'])
def ssubmit_and_confirm():
"submit an event and display confirmation"
if request.method == 'POST':
return redirect(url_for('confirm', value=value))
The below code is the confirmation.html page
<body style="background-color:powderblue;">
<div class="panel panel-default" style="max-width:1000px;max-height: 800px;margin-left:auto;margin-right:auto;">
<div class="panel-heading " style="text-align: center;">submit student details</div>
<div class="panel-body" id="resultDiv">
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-body">
<label class="col-md-8" for="Date:">Date:
{{ value }}</br> Time :{{value}}</label>
<label class="col-md-8" for="dateApplied"></label>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<label class="col-md-8" for="student email:">
student email id:{{value}}</label>
</div>
</div>
</div>
</div>
</body>
So the problem here is once I come to the confirmation.html and if I click the browser back button it goes to the form and it lets me add the same details.
To avoid this I tried including this lines in the confirmation.html
</div>
<div><input type="hidden" id="reloadPage" /></div>
<script type="text/javascript">
$(document).ready(function() {
function reloadPage(){
location.reload(true); ; // RELOAD PAGE ON BUTTON CLICK EVENT.
// SET AUTOMATIC PAGE RELOAD TIME TO 5000 MILISECONDS (5 SECONDS).
var timerId = setInterval('refreshPage()', 5000);
}
});
function refreshPage() { clearInterval(timerId); location.reload(); }
</script>
But it's not working. I tried one more method which is given in the link
How to stop re submitting a form after clicking back button
This is also not working.
So what do I need is if I click the back button in the browser I should display the confirmation page only or it should tell this is not the authourized page.
Step 1:
On the form submission page, initially set the form submission value to false.
sessionStorage.setItem('form-submit', false)
Step 2:
And when submitting the form in previous page, check:
function submitEvent() {
formSubmitted = sessionStorage.getItem('form-submit')
if (!formSubmitted){
// Write your code here
}
}
Step 3:
On confirmation.html page, you can store a submission value in sessionStorage.
sessionStorage.setItem('form-submit', true)
You could add HTML5 history api. Use following code .
name = document.title
history.pushState(null,name,name)//add this code in your configuration.html file in document ready block
$(window).on("popstate",()=>{
//....Do whatever you want
/*If you want to display unauthorized page then
$(document).html("Unauthorized page")
*/
})
store the form data and reset the form just before the form data is sent to the server. Assuming that you are using $.ajax() to submit the form.
function submitEvent() {
form = document.createElement("form");
form.method = "POST";
form.action = "/confirmation";
// Add id attribute to the form
form.id = "student_details_form";
// Collect form data
// reset your form just before calling $.ajax() or $.post()
document.getElementById('student_details_form').reset();
// call $.ajax() or $.post()
$.ajax({
url: form.action,
// snipps
};
}
With a list of products, and once a 'remove from wishlist' button is clicked, it then removes that product from said product list, along with an AJAX request to the back-end for it to be removed via SQL.
The first click works, the jQuery executes and the product is then removed. The second click on the same type of button for any product, then loads the href instead of executing the jQuery, it's meant to execute the jQuery.
I've tried calling it as a static function from the anchor onclick="return removeFromWishlist();"
Have also tried executing the jQuery on the anchor link click via the jQuery event instead of the button tag itself.
jQuery('.button-wishlist').on('click', function (index) {
event.preventDefault();
// Calls the AJAX to remove it from the back-end via SQL etc
// The response is JSON within the following call
removeProductAjax(this);
console.log('removing product from the wishlist');
// Get the cell position of the product to remove from the wishlist
var position = jQuery(this).parent().parent().parent().data('cell');
var html = [];
var cells = 0;
jQuery('.wishlist_container .col-md-4').each (function () {
//
if (jQuery(this).data('cell') == position) {
cells++;
}
else if (jQuery(this).data('cell') !== undefined) {
html.push(jQuery(this).html());
cells++;
}
});
var upto = 0;
jQuery('.product-row').each (function () {
var self = this;
// Repopulate all the product lists excluding the one removed
jQuery(self).children().each (function () {
jQuery(this).html(html[upto]);
upto++;
});
});
// Then clear everything from upto and onwards!
console.log('cells: ' + cells);
console.log('upto: ' + upto);
// let's change from array to 'standard' counting
upto--;
// Remove the last element!
jQuery('.product-row').find('[data-cell=' + upto + ']').remove();
// Check for any empty rows
jQuery('.product-row').each (function () {
if (jQuery(this).children().length == 0) {
jQuery(this).remove();
}
});
});
The HTML is basically:
<div class="row product-row">
<div class="row product-row"><div class="col-md-4" data-cell="0">
<h1>product 1</h1>
<a href="./page.php?page=cart&unwish=660986" data-index="660986" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
<button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
</a>
</div>
<div class="col-md-4" data-cell="1">
<h1>product 2</h1>
<a href="./page.php?page=cart&unwish=661086" data-index="661086" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
<button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
</a>
</div>
<div class="col-md-4" data-cell="2">
<h1>product 3</h1>
<a href="./page.php?page=cart&unwish=661067" data-index="661067" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
<button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
</a>
</div>
</div>
I'm expecting it to execute the jQuery each time the "remove from wishlist" button is clicked, no matter what product, no matter what order. So, you can unwish many products, one after the other using AJAX / jQuery.
Follow all my comments under your Question...
And I think this is all the code you need.
PHP (I used i.e: ../removeProduct.php?id=) should respond with some JSON like:
// PHP does here some DB deletions or fails.
// Send back to AJAX the deleted item ID (or null)
// and some (error?) message
echo json_encode(['id' => $id, 'message' => $message]);
exit;
// No more PHP here. We exit.
// jQuery will collect that JSON response as `res`
jQuery(function($) {
function removeProductAjax(id) {
$.get("../removeProduct.php?id=" + id, 'json').always(function(res) {
if (res.statusText === 'error') { // General error (path invalid or something...)
return alert(`Error: Cannot remove product ID: ${id}`); // and exit function
}
if (!res.id) { // Something happened
return alert(res.message); // Alert PHP's error message and exit function.
}
// All OK. Remove item from products
$(".product-row").find(`[data-id="${res.id}"]`).remove();
});
}
$('.product-row').on('click', '.product-remove', function(ev) {
ev.preventDefault();
removeProductAjax($(this).data('id'));
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<div class="row product-row">
<div class="col-md-4" data-id="660986">
<h3>product 1</h3>
<button type="button" class="btn product-remove" data-id="660986">Remove from Wishlist</button>
</div>
<div class="col-md-4" data-id="661086">
<h3>product 2</h3>
<button type="button" class="btn product-remove" data-id="661086">Remove from Wishlist</button>
</div>
<div class="col-md-4" data-id="661067">
<h3>product 3</h3>
<button type="button" class="btn product-remove" data-id="661067">Remove from Wishlist</button>
</div>
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
I have the following controller:
function _deleteServiceInstance(serviceInstanceId) {
self.hasServerErrors = false;
self.serverErrors = [];
var flag = 1;
if (confirm("Are you sure you want to delete the service instance in this environment region?")) {
for (var i = 0; i < self.serviceInstanceDeployments.length; i++) {
var obj = self.serviceInstanceDeployments[i];
if (obj.state === "ACTIVE")
flag = 0;
}
if (flag === 0)
{
self.hasServerErrors = true;
self.serverErrors = ["Please delete the active deployments before deleting the service instance"];
// $window.location.reload();
$scope.$apply();
return self.serverErrors;
};
}
}
The following is the HTML:
<a uib-popover-template="ctrl.deleteServiceInstanceTemplate" popover-title="Delete service instance"
popover-placement="auto bottom" popover-trigger="outsideClick">
<button type="button" class="btn btn-danger">
Delete
</button>
</a>
<script type="text/ng-template" id="deleteServiceInstance.html">
<div class="container-fluid">
<div class="row">
<form name="ctrl.delete.form" class="form-horizontal" novalidate>
<div class="form-group" ng-class="{'has-error' : ctrl.hasServerErrors}">
<label class="col-sm-12 control-label">Are you sure?
<button type="submit" class="btn btn-primary" ng-click="ctrl.deleteServiceInstance(ctrl.serviceInstance.id)"
ng-disabled="ctrl.purge.form.$invalid">Yes</button>
<span ng-show="ctrl.hasServerErrors" class="help-block" ng-repeat="serverError in ctrl.serverErrors">{{serverError}}</span>
</label>
</div>
</form>
</div>
</div>
</script>
Basically, there is a delete button which opens as a pop-up. It asks for confirmation if I am sure of deleting something. If I press yes, it checks if there are any deployments in active state. If there are, it shows an error. Now, the problem is, when I click on the delete button for the second time, it shows the same error even when I haven't pressed yes. It keeps on showing the same error until the page is refreshed.
Edit: I have declared the _deleteServiceInstance like this in my controller:
self.deleteServiceInstance = _deleteServiceInstance
You should clear the messages while clicking the delete button event, instead of yes button click event
<button type="button" ng-click="clearMessages" class="btn btn-danger">
Delete
</button>
Controller
function _clearMessages() {
self.hasServerErrors = false;
self.serverErrors = [];
}
self.clearMessages= _clearMessages
I'm using VB.Net, MVC 5, razor and jQuery. I have a razor view that creates buttons I'm trying to disable on the user click. I generally accomplish this task using jQuery:
$('#id').prop("disabled", true);
My task is new to me in that my buttons are generated like this:
#For i As Integer = 0 To Model.hrmnValues.Count - 1
#<div class="col-md-3">
<a class="btn btn-primary btn-md" href="#" id="#Model.inventoryCategoryAttIDs(i)"
onclick="acceptChange('#Model.hrmnValues(i)',
#Model.inventoryCategoryAttIDs(i), #Model.uniqueItemID)">Accept Change</a>
</div>
Next
My onClick function is similar to this:
function acceptChange(newValue, categoryAttID, itemID) {
$('#categoryAttID').prop("disabled", true);
}
This obviously does not work, as it is looking for an id with the name of categoryAttID. I have also tried putting the categoryAttID into it's own variable like this:
var idToDisable = "#" + categoryAttID;
and then putting idToDisable into the jQuery call to disable the button, this did not work.
Given this situation how can I disable the button that is clicked?
There will be multiple buttons on this page making use of the function, the function actually performs an ajax call. The idea is to limit the user to performing one ajax call per button.
The html is rendered like this:
<div class="row">
<div class="col-md-3">
<font>First Name</font>
</div>
<div class="col-md-3">
<font>John</font>
</div>
<div class="col-md-3">
<font>No Record Found</font>
</div>
<div class="col-md-3">
<a class="btn btn-primary btn-md" href="#" id="2"
onclick="acceptChange('CHRISTOPHER', 2, 0)">Accept Change</a>
</div>
</div>
<div class="row">
<div class="col-md-3">
<font>Last Name</font>
</div>
<div class="col-md-3">
<font>MURRAY</font>
</div>
<div class="col-md-3">
<font>No Record Found</font>
</div>
<div class="col-md-3">
<a class="btn btn-primary btn-md" href="#" id="3"
onclick="acceptChange('MURRAY', 3, 0)">Accept Change</a>
</div>
You're already passing the button's id to your function as the second argument -
acceptChange('#Model.hrmnValues(i)',#Model.inventoryCategoryAttIDs(i), #Model.uniqueItemID)
So you can change your function to -
function acceptChange(newValue, categoryAttID, itemID) {
$('#' + categoryAttID).prop("disabled", true);
}
Also, there isn't a disabled property available for links (see - Mozilla Developer Network) if you want to disable your elements on click try using a button instead.
Since you appear to be using bootstrap after changing your links to buttons you might want to change your function to -
function acceptChange(newValue, categoryAttID, itemID) {
$('#' + categoryAttID).prop("disabled", true);
$('#' + categoryAttID).addClass("disabled");
}