As a beginner on the client-side, I am currently grasping the concepts of Ajax and could use some clarification.
e.preventDefault();
is a common method used to prevent form submission (which causes a page refresh) in JavaScript.
An example where this comes in handy is when submitting a form using Ajax. Here is some sample code:
function cancel_default_submission(e) {
// stop the default behavior
e.preventDefault();
// create and fill the form with data
var form_data = new FormData();
form_data.append("reply", text_field.value);
// send the form using AJAX
var xhr = new XMLHttpRequest();
xhr.open('POST', e.target.action);
xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken'));
xhr.send(form_data);
}
I have two questions:
1) Let's say the POST
request is sent to a function that ultimately has a redirect
statement to a different URL. In the case of using Django for web development, an example would be return redirect("home")
wherein "home" is the home page of the application. How does preventDefault()
prevent the execution of the redirect
statement in server-side code? I'd like to delve into the mechanics behind this.
2) What if one wants the page to refresh (or redirect) as usual after an Ajax POST request? What modifications are needed? An illustrative example would greatly help clarify my understanding.
I am familiar with Django (Python), so showcasing server-side code using Django would be ideal.
Note: I prefer focusing on pure JavaScript for now as I am still learning. While JQuery is on my radar, I plan to master JS fundamentals first.