简体   繁体   中英

Submitting form using Sweet Alert (aka Swal)

I'm using Swal to replace all JavaScript default alerts and stuffs. There's a form on one of my pages for which also I'm using Swal to ask the user to confirm his action (deleting a file) before making it happen.

The problem is I can not get the form working. Here's the Swal code:

jQuery('.deleteFile').click(function(event){
    event.preventDefault();
    swal({
        title: "You sure about deleting this file?",
        icon: "warning",
        buttons: {
            cancel: "hmm let me think this through",
            confirm: "100% sure !",
        },
        dangerMode: true,
    })
    .then((willDelete) => {
        if (willDelete) {
            $('#form1').submit();
        } else {
            return false;
        }
    });
});

And this is my submit button:

<button type="submit" name="delete_file" class="btn btn-danger deleteFile">Delete</button>

There are few things to mention here :

  • I'm totally a newbie when it comes to JavaScript / jQuery. So if you notice any hilarious mistake here, pardon my rookieness <3

  • I searched a lot about this and tried out all the suggestions that I found, like using the isConfirm function suggested by many users. But none worked. The use of isConfirm function actually bugs the entire code and even the alert part doesn't pop up.

  • The .then((willDelete) part of the code is the Swal's default code, which actually works fine.

  • The class deleteFile is pointing to the submit button. The ID form1 points to the form itself.

  • At the current state of the code, when the user presses confirm button, the page refreshes, looking like it has done the job. But it's actually not working. I've written the following code to test it out :

     if(isset($_POST['delete_file'])){ echo 'WOOT IT WORKED!'; } 

But it doesn't echo anything (QQ)

Needless to say that delete_file is the name attribute of my submit button.

Needless to say that delete_file is the name attribute of my submit button.

Well that is the problem. The name of your submit button is only submitted if you click that button. If you submit a form with JavaScript, the submit button name and value are not submitted.

To prevent this you can, instead of having the name/value in the submit button, add them to a hidden input like so:

<input type="hidden" name="delete_file" value="Delete">

Or you can check if another field is set, like the id of the file you want to delete in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM