Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent from submiting form several times by clicking fast in laravel

Tags:

forms

php

laravel

So I ran into issue, that If i click fast enough subnmit button, my form is submited several times. How can I prevent this? Token is added automatically, but it doesnt help at all I guess. Form example:

  <div class="row padding-10">
    {!! Form::open(array('class' => 'form-horizontal margin-top-10')) !!}
    <div class="form-group">
      {!! Form::label('title', 'Title', ['class' => 'col-md-1 control-label padding-right-10']) !!}
      <div class="col-md-offset-0 col-md-11">
      {!! Form::text('title', null, ['class' => 'form-control']) !!}
      </div>
    </div>
    <div class="form-group">
      {!! Form::label('body', 'Body', ['class' => 'col-md-1 control-label padding-right-10']) !!}
      <div class="col-md-offset-0 col-md-11">
      {!! Form::textarea('body', null, ['class' => 'form-control']) !!}
      </div>
    </div>
    <div class="col-md-offset-5 col-md-3">
      {!! Form::submit('Submit News', ['class' => 'btn btn-primary form-control']) !!}
    </div>
    {!! Form::close() !!}
  </div>

My NewsController store method:

    public function store()
{
$validator = Validator::make($data = Input::all(), array(
  'title' => 'required|min:8',
  'body' => 'required|min:8',
));

if ($validator->fails())
{
  return Redirect::back()->withErrors($validator)->withInput();
}

News::create($data);

return Redirect::to('/news');
}
like image 611
Dancia Avatar asked Dec 05 '25 13:12

Dancia


2 Answers

One approach is to use a click handler for the button where it first disables the button, then submits the form.

<script>
    function submitForm(btn) {
        // disable the button
        btn.disabled = true;
        // submit the form    
        btn.form.submit();
    }
</script>

<input id="submitButton" type="button" value="Submit" onclick="submitForm(this);" />
like image 200
snow_FFFFFF Avatar answered Dec 07 '25 03:12

snow_FFFFFF


Step 1: write a class name in the form tag Exp: "from-prevent-multiple-submits"

<form class="pt-4 from-prevent-multiple-submits" action="{{ route('messages.store') }}" method="POST">
 @csrf

Step 2: write a class in button section

<button type="submit" id="submit" class="btn btn-primary from-prevent-multiple-submits">{{ translate('Send') }}</button>

Step 3: write this script code

(function(){
$('.from-prevent-multiple-submits').on('submit', function(){
    $('.from-prevent-multiple-submits').attr('disabled','true');
})
})();
like image 44
Tanvir Rahman Prince Avatar answered Dec 07 '25 04:12

Tanvir Rahman Prince



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!