How do I show a confirmation dialog before submitting a form using the jQuery ajax method?

user272899 picture user272899 · Feb 18, 2010 · Viewed 12.9k times · Source

I am using jquery ajax to delete a customer from a table. How would I show a confirmation box before submitting the form? I would preferably like to use jQuery's dialog.

I have seen questions like this before but none of them have helped.

This is my code:

    $.ajax({
        type: "POST",
        url: "delete/process.php",
        data: "delcustomerid="+ delcustomerid,
        success: refreshTable
    });

Answer

casperOne picture casperOne · Feb 18, 2010

The ajax function has a beforeSend event which you can use to show the dialog before the form is submitted.

If the dialog indicates that the form should not be submitted, then you would return false from your function so that the submission of the form does not take place.

In your case, you would do the following:

$.ajax({ 
    beforeSend: function (request) {
        // This is where you show the dialog.
        // Return false if you don't want the form submitted.
    },

    type: "POST", 
    url: "delete/process.php", 
    data: "delcustomerid="+ delcustomerid, 
    success: refreshTable 
});

If you are issuing a POST for the form (which it seems you are), I highly recommend you take a look at the jQuery form plugin as it simplifies the process of submitting forms through AJAX calls a great deal for you, and uses all the same parameters a call to ajax does.