forked from code-dot-org/code-dot-org
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathajaxSubmit.js
More file actions
31 lines (30 loc) · 1.11 KB
/
ajaxSubmit.js
File metadata and controls
31 lines (30 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import $ from 'jquery';
module.exports = function ajaxSubmit(form_selector) {
$(document).ready(function () {
$(form_selector).on('ajax:beforeSend', function (e, xhr) {
$('.validation-error').empty();
var token = $('meta[name="csrf-token"]').attr('content');
xhr.setRequestHeader('X-CSRF-TOKEN', token);
});
$(form_selector).on('ajax:complete', function (e, data) {
if (parseInt(data.status, 10) === 200) {
localStorage.removeItem('markdown_' + window.location.pathname.split('/').reverse()[1]);
window.location.href = JSON.parse(data.responseText).redirect;
}
});
$(form_selector).on("ajax:error", function (evt, xhr, status, error) {
var errors;
try {
errors = $.parseJSON(xhr.responseText);
} catch (err) {
errors = {message: "Error (" + error + "): " + xhr.responseText};
}
$('.validation-error')
.html("<p>Couldn't create level:</p>")
.append($("<ul/>")
.append(Object.keys(errors).map(function (v) {
return $("<li/>").text(v + ": " + errors[v]);
})));
});
});
};