1

Given the form ajax like this

<form method="post"
        data-ajax="true" 
        data-ajax-method="post" 
        data-ajax-complete="completed" 
        data-ajax-confirm="Are you sure you want to do this?">
    <input type="text" name="name" /><input type="submit"/>
</form>

I already set data-ajax-confirm, but any idea how to implement with sweetalert?

Example

<script>
swal({
  title: "Are you sure?",
  text: "Once deleted, you will not be able to recover this imaginary file!",
  icon: "warning",
  buttons: true,
  dangerMode: true,
})
.then((willDelete) => {
  if (willDelete) {
    //Submit ajax here
  } else {
    swal("Your imaginary file is safe!");
  }
});

completed = function (xhr) {
            if (xhr.status == "200") {
                swal("Success", xhr.responseText, "success")
                    .then(() => {
                        location.reload();
                    });
            }
            else {
                swal("Error", xhr.responseText, "error")
            }

        };
</script>

How to display dialog box with sweetalert before submit

Azri Zakaria
  • 1,324
  • 5
  • 23
  • 52

1 Answers1

1

You can do it just like below:

<form method="post"
      id="myform"
      data-ajax="true"
      data-ajax-method="post"
      data-ajax-complete="completed">
    <input type="text" name="name" />
</form>

<input id="submit" type="button" value="submit" />

Scripts:

@section scripts{
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
    <script src="~/lib/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.js"></script>
    <script>
        $("#submit").click(function () {
            swal({
                title: "Are you sure?",
                text: "Once deleted, you will not be able to recover this imaginary file!",
                icon: "warning",
                buttons: true,
                dangerMode: true,
            })
                .then((willDelete) => {
                    if (willDelete) {
                        $("#myform").submit();
                    } else {
                        swal("Your imaginary file is safe!");
                    }
                });

            completed = function (xhr) {
                if (xhr.status == "200") {
                    swal("Success", xhr.responseText, "success")
                        .then(() => {
                            location.reload();
                        });
                }
                else {
                    swal("Error", xhr.responseText, "error")
                }
            };
        })
    </script>
}

Controller:

public IActionResult Index()
{
    return View();
}

[HttpPost]
public IActionResult Index(string name)
{
    if(name != null)
    {
        return Ok();
    }
    return NotFound();
}

Result:

enter image description here

mj1313
  • 7,930
  • 2
  • 12
  • 32