XF 2.3 Cancelling form submit by `e.preventDefault()` is not working

BredyAK

Member
I'm trying to create a plugin. I want to use js to cancel a form submit by following code:
JavaScript:
XF.on(form, 'ajax-submit:before', XF.proxy(this, 'beforeSubmit'));
// ...
function beforeSubmit(e) {
    console.log('beforeSubmit:', this.submitting);
    e.preventDefault();
    this.submitting = true;
}

Expected: When I click the submit button, it won't submit and console logs beforeSubmit: false.

Actually: Console shows beforeSubmit: false, but then it was submitted.

XenForo version: 2.3.7
 
In XenForo 2.3, the ajax-submit:before event uses a CustomEvent where the prevention mechanism isn't just e.preventDefault(). You need to set a flag on the event's detail object.
Code:
function beforeSubmit(e) {
    console.log('beforeSubmit:', this.submitting);
    e.preventDefault();
    e.preventSubmit = true;
    this.submitting = true;
}

If that doesn't work, try accessing through the detail property:

Code:
function beforeSubmit(e) {
    console.log('beforeSubmit:', this.submitting);
    e.preventDefault();
    if (e.detail) {
        e.detail.preventSubmit = true;
    }
    this.submitting = true;
}

The XenForo Form handler checks for this preventSubmit flag in addition to (or instead of) the standard defaultPrevented property when determining whether to proceed with the AJAX submission.
 
Back
Top Bottom