Randy Tang
Randy Tang

Reputation: 4353

jQuery confirm and then post with ajaxForm

The following jQuery code executes the ajaxForm function even if I press the Cancel button. In addition, the success part doesn't update the content, either. Can anybody tell me what's wrong with it? Thanks.

$(document).ready(function() {
  $(".myForm").click(function (e) {
    if (confirm("Are you sure?")) {
      $(".myForm").ajaxForm ({
        success: function(returnData) {
          $('#content').html(returnData);
        }
      });
    }
  });
});

Upvotes: 1

Views: 1568

Answers (1)

John S
John S

Reputation: 21482

The click event should be set on a button element, and you should use .ajaxSubmit(), rather than .ajaxForm().

Either the button should not be a submit button (that is, <input type="submit"> or <button type="submit">) or else you need to call e.preventDefault().

Try something like this:

HTML:

<form id="myForm">
    <input type="text" />
    <button type="submit" id="submitButton">Submit</button>
<form>

JavaScript:

$('#submitButton').click(function(e) {
    e.preventDefault();
    if (confirm('Are you sure?')) {
        $("#myForm").ajaxSubmit({
            success: function(returnData) {
                $('#content').html(returnData);
            }
        });
    }
});

Upvotes: 2

Related Questions