Skip to content
This repository has been archived by the owner on Nov 19, 2018. It is now read-only.

Commit

Permalink
feat(submitting): allow form submit to be cancelled
Browse files Browse the repository at this point in the history
closes #54
  • Loading branch information
Ray Nicholus committed May 12, 2015
1 parent f13b0db commit 9d1ecb5
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 12 deletions.
3 changes: 3 additions & 0 deletions ajax-form.html
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,9 @@
* If you would like to modify or add to the form data before it is sent
* to the server, do so here by making changes directly to `detail.formData`.
*
* To prevent the form from being submitted, simply invoke the `preventDefault()`
* function on the `Event` object passed into your handler function.
*
* NOTE: Do not deviate from the flat structure of the data unless the `enctype`
* is "application/json". Doing so for other encoding types may produce surprising
* results.
Expand Down
26 changes: 14 additions & 12 deletions ajax-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,22 +232,24 @@
formData = parseForm(ajaxForm, enctype === 'multipart/form-data'),
submittingEvent = fire(ajaxForm, 'submitting', {formData: formData});

formData = submittingEvent.detail.formData;
if (!submittingEvent.defaultPrevented) {
formData = submittingEvent.detail.formData;

if ('multipart/form-data' !== enctype &&
'application/json' !== enctype) {
if ('multipart/form-data' !== enctype &&
'application/json' !== enctype) {

sendUrlencodedForm(ajaxForm, formData);
}
else {
if ('GET' === ajaxForm.acceptableMethod) {
sendUrlencodedForm(ajaxForm, formData);
}
else if ('multipart/form-data' === enctype) {
sendMultipartForm(ajaxForm, formData);
}
else if ('application/json' === enctype) {
sendJsonEncodedForm(ajaxForm, formData);
else {
if ('GET' === ajaxForm.acceptableMethod) {
sendUrlencodedForm(ajaxForm, formData);
}
else if ('multipart/form-data' === enctype) {
sendMultipartForm(ajaxForm, formData);
}
else if ('application/json' === enctype) {
sendJsonEncodedForm(ajaxForm, formData);
}
}
}
},
Expand Down
13 changes: 13 additions & 0 deletions test/typical-form-tests.html
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,19 @@
ajaxForm.submit();
})
});

it('prevents a form from being submitted if the submitting event\'s default action is prevented', function (done) {
createForm({method: 'GET'}, function () {
ajaxForm.addEventListener('submitting', function (event) {
event.preventDefault();
});

ajaxForm.submit();

expect(requests.length).to.equal(0);
done();
});
});
});

describe('url encoding', function () {
Expand Down

0 comments on commit 9d1ecb5

Please sign in to comment.