Search code examples
laravelbuttonalertconfirmationcancel-button

Confirmation window "Cancel" button not working


I'm building my first laravel project and I'm trying to make a confirmation window for my "Delete" button. The thing is that confirmation window shows up, but whether I press "confirm" or "cancel" it would delete data anyway. Can you help me out?

Here is my code:

<a id="demo" href="{{route('viewfile2.delete2', $down->id)}}?{{time()}}">
  <button type="submit" class="btn btn-primary" style="background-color:red;"onclick="myFunction()">
      Delete
    </button>
</a>
                      
    
    
    <script>
        function myFunction(){
        	return confirm('Are you sure?');
    }
    </script>


Solution

  • To prevent your form submitting data, replace type="submit" by type="button" and replace your JavaScript code by testing the return value of the confirm call, if it's true then submit your form programmatically.

    For testing purposes I made this:

        <form id="deleteFormId" action="http://yourwebsite.kom/doDelete/4598765">
        <button type="button" onclick='myFunction()'>Delete</button>
        </form>
          </body>
        </html>
    
        <script>
        function myFunc(){
        if (window.confirm("Are You Sure ?")) { 
          document.querySelector('#deleteFormId').submit();
        }
        }
        </script>
    

    See the Codepen example and Document.querySelector() documentation.