Last active
May 9, 2020 09:13
-
-
Save LouisdeBruijn/f247fbcdcdc3ad4b306771eeed69b4f2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $('#contact-form-button').click(function(event){ | |
| event.preventDefault(); // prevent default submit event that would automatically reload webpage | |
| // initalizing variables | |
| const form = $('#contact-form'); | |
| const url = form.prop('action'); // the url to redirect to "/contact" | |
| const type = form.prop('method'); // the method "POST" or "GET" | |
| const data = new FormData(form); // formData object with all key ("id" attribute)-value("user input") pairs | |
| $.ajax({ | |
| url: url, | |
| type: type, | |
| data: formData, | |
| processData: false, | |
| contentType: false, | |
| beforeSend: function() { | |
| // show the preloader (progress bar) | |
| $('#form-response').html("<div class='progress'><div class='indeterminate'></div></div>"); | |
| }, | |
| complete: function () { | |
| // hide the preloader (progress bar) | |
| $('#form-response').html(""); | |
| }, | |
| success: function ( response ){ | |
| // object has been returned from backend | |
| // object contains key-value pairs in an object | |
| // these keys 'feedback' and 'content' are set in the backend | |
| if ( !$.trim( response.feedback )) { // empty response from backend | |
| error_msg = "An empty response was returned."; | |
| } | |
| else { // non-empty response | |
| error_msg = response.feedback; | |
| // load content by | |
| $('#form-content').html(response.content); | |
| } | |
| }, | |
| error: function(xhr) { // an error occured | |
| // logging the error | |
| console.log("error. see details below."); | |
| console.log(xhr.status + ": " + xhr.responseText); | |
| // returning user-feedback | |
| error_msg = "An error occured"; | |
| }, | |
| }).done(function() { | |
| // this part is always executed, even when the AJAX request was not succesfull | |
| $('#form-response').append(error_msg); | |
| }); | |
| }; | |
| // Flask's way of adding a csrf token to the AJAX request | |
| var csrf_token = "{{ csrf_token() }}"; | |
| // set the CRSF token in the request headers | |
| $.ajaxSetup({ | |
| beforeSend: function(xhr, settings) { | |
| if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) { | |
| xhr.setRequestHeader("X-CSRFToken", csrf_token); | |
| } | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment