How to prevent multi-click from submit with PHP?
It can be done in PHP, but I'd say your easiest option is to use javascript, and to simply disable the submit button on the first click.
Vanilla JS:
document.getElementById("yourButton").disabled = true;
jQuery:
$('#yourButton').attr("disabled", true);
Attach either function to your button's click event, and you're all set!
How to prevent multiple form submissions in PHP
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.
How to prevent submit by double click
You can use the ActiveForm
's js event beforeSubmit
to disable the button at the time the form is submitted, you can use CSS pointerEvents:'none'
to disable the click on the button.
Assing an id="my-form"
to your form and id="my-submit"
to your submit button and use the below script on top of your view and your button will be disabled at the time of submission.
$js =<<< JS
$("#my-form").on("beforeSubmit",function(e){
e.preventDefault();
$("#my-submit").css({pointerEvents:'none'});
return true;
});
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
prevent multiple submissions when user clicks submit button multiple times before loading to the new page
If this is the buttton:
<input type="submit" name="submit" value="submit" id="preventDouble">
With jQuery:
$("#preventDouble").on("submit",function(){
$(this).unbind("submit");
$(this).on("submit",function(){return false;});
};
After the first submit, jQuery will attach an event that will cancel further submits.
Note that this event does not check if the form was actually successfully submited to the server.
This may answer your question, but it's a safer and better approach to track multiple submits on the server, e.g. adding a "last_submitted" attribute to the session, and prevent further submits if datetime.datetime.now is less than 1 minute from session.last_submitted:
import datetime
import pickle
def form_valid(self,form):
if not hasattr(self.request.session['last_submitted']):
last_submitted = pickle.dumps(datetime.datetime.now())
self.request.session['last_submitted'] = last_submitted
save_it = True
else:
last_submitted = pickle.loads(self.request.session['last_submitted'])
delta = datetime.datetime.now() - last_submitted
save_it = (delta.seconds > 60): # assume allow re-submit after 60 seconds
if save_it:
self.object = form.save(commit=False)
# any manual settings go here
#self.object.category = Category.objects.filter(category__in=categories).all()
self.object.moderator = self.request.user
self.object.image = extract(self.object.url)
self.object.thumbnail = extractt(self.object.content)
self.object.save()
return HttpResponseRedirect(reverse('post', args=[self.object.slug]))
else:
# consider redirect as usual, if the user just clicked twice by mistake
return self.form_invalid(form) # or Http error code
Edit
import datetime
import pickle
class PostCreateView(CreateView):
model = Post
form_class = PostForm
template_name = 'main/add_post.html'
def form_valid(self,form):
if not hasattr(self.request.session['last_submitted']):
last_submitted = pickle.dumps(datetime.datetime.now())
self.request.session['last_submitted'] = last_submitted
save_it = True
else:
last_submitted = pickle.loads(self.request.session['last_submitted'])
delta = datetime.datetime.now() - last_submitted
save_it = (delta.seconds > 60) # assume allow re-submit after 60 seconds
if save_it:
self.object = form.save(commit=False)
# any manual settings go here
#self.object.category = Category.objects.filter(category__in=categories).all()
self.object.moderator = self.request.user
self.object.image = extract(self.object.url)
self.object.thumbnail = extractt(self.object.content)
self.object.save()
return HttpResponseRedirect(reverse('post', args=[self.object.slug]))
else:
# consider redirect as usual, if the user just clicked twice by mistake
return self.form_invalid(form) # or Http error code
Related Topics
PHP Session Data Not Being Saved
Does PHP Time() Return a Gmt/Utc Timestamp
MySQLi Count(*) Always Returns 1
Is There a PHP Equivalent of Perl'S Www::Mechanize
Fatal Error: Class 'PHPmailer' Not Found
Setting the PHP Default Encoding to Utf-8
How to Check If an Array Contains a Specific Value in PHP
Checking If Customer Has Already Bought Something in Woocommerce
PHP Fatal Error: Call to Undefined Function Mssql_Connect()
Is MySQL_Real_Escape_String() Broken
Creating Jquery Ajax Requests to a PHP Function
How to Replace MySQL Functions With Pdo
The Holy Grail of Cleaning Input and Output in PHP
Difference in Accessing Arrays in PHP 5.3 and 5.4 or Some Configuration Mismatch
When Should I Use Memcache Instead of Memcached
What Is Autoloading; How to Use Spl_Autoload, _Autoload and Spl_Autoload_Register