Make The SweetAlert Visible when i submit the form

Viewed 402

I Am Presently Working On a Flask Project where I need to post a Form and I Show a SweetAlert as soon as the form is posted. But the Problem is As Soon as The Swal Method is Triggered, the Post Method Occurs and Returns to The Same Page which is Set Using Flask. I want to Refresh the Page after the SweetAlert shows and the user clicks on the Ok Button.

Here is my code:

 if (k > 0) {
    e.preventDefault();
  } else {
    swal({
      title: "Thank You",
      text: "You Would Be Notified Soon",
      icon: "success",
    });
  }
});

and My Python Backend:

if request.method == "POST":
        email = request.form['email']
        link = request.form['link']
        crntprice = int(request.form['crntprice'])
        btn_group = request.form.getlist("btn_group")
        change_price = False
        if "change_in_price" in btn_group:
            change_price = True
        tgt_price = 0
        if "btn_change_price" in btn_group:
            tgt_price = int(request.form['tgt_price'])
        item = Prices(email=email, link=link, crnt_price=crntprice,
                      change_price=change_price, lower_price=tgt_price)
        try:
            db.session.add(item)
            db.session.commit()
            return redirect('/')
        except:
            return "Error"
    else:
        return render_template("index.html")

I just want to trigger the Post-event after the user clicks ok on the sweet alert.

1 Answers

Try this solution:

swal({
            title: "...",
            text: "Are you sure you want to...?",
            type: "success",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "No"
        }).then(result => {
            if (
                result.dismiss !== swal.DismissReason.cancel &&
                result.dismiss !== swal.DismissReason.backdrop
            ) {
                return this.genericService
                    .servicePost("/endpoint", payload)
                    .subscribe(data => {
                        if (data) {
                            swal({
                                position: "center",
                                type: "success",
                                title: "...",
                                showConfirmButton: false,
                                timer: 1500
                            });

                           
                        } else {
                            swal({
                                title: "Erreur!",
                                text:
                                    "An error has occurred",
                                type: "error",
                                confirmButtonText: "ok"
                            });
                        }
                    });
            }
        });

Related