jquery: ajax POST inside a form – prevent form submission on ajax call

You need to override form’s onsubmit event to prevent submitting:

$("formSelector").bind('submit', function (e) {
    var isValid = someYourFunctionToCheckIfFormIsValid();
    if (isValid) {
        jQuery.ajax({
            type: "POST",
            url: "my_custom/url",
            dataType: "html",
            data: { "text": jQuery("#edit-body").html()
            },
            success: function (result) {
                console.log(result);
            }
        });
    }
    e.preventDefault();
    return false;
});

By calling

e.preventDefault();
return false;

You prevent synchronous postback from occurring.

UPDATE:
If you don’t want to override form submit, maybe you could place your button outside of form tag (you can adjust position with css if necessary)?

Leave a Comment