Reputation: 15824
I'm a client-side newbie learning the ropes, and need to clarify Ajax concepts.
e.preventDefault();
is a typical method of preventing form submission (page refresh) in JS.
One use case where the above is handy is Ajax-based form submission. Sample code is:
function overwrite_default_submit(e) {
// block the default behavior
e.preventDefault();
// create and populate the form with data
var form_data = new FormData();
form_data.append("reply", text_field.value);
// send the form via 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) Imagine the POST
request is being sent to a function that ends with a redirect
to a different URL. For example, I use Django to develop web applications; a typical Django view may end up with return redirect("home")
where home is the home page of the said app. In such a scenario, how does preventDefault()
prevent the redirect
statement in server-side code from executing? I'm trying to understand the exact mechanics behind it.
2) What if one wanted page refresh (or redirect) to proceed normally after an Ajax POST request? What tweaks need to be made? Would love to see an illustrative example to clarify my concepts.
I'm well-versed in Django (Python) so in case you need to show server-side code, Django would be a good example.
Note: prefer to stick to pure JS for this, since I'm learning JS these days. JQuery's on my radar, but only after I've mastered the fundamentals of JS.
Upvotes: 1
Views: 2905
Reputation: 3005
The preventDefault()
cancels the event, Default action that event of element will not occur. This will simply halt further execution of javascript code after that statement.
For i.e.
- Clicking on a submit
button, prevent it from submitting a form.
- Clicking on a link
, prevent the link
from following the given
URL
To redirect to the next page or to add notification or may be to add html through javascript, but here is to redirect only.
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) //Here we need to check OK response and last state of ajax call.
{
window.location.href = 'REDIRECT_URL'
window.location.reload() // To refresh page.
}
};
=== I've added that in your function ===
function overwrite_default_submit(e)
{
// block the default behavior
e.preventDefault();
// create and populate the form with data
var form_data = new FormData();
form_data.append("reply", text_field.value);
// send the form via AJAX
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) //Here we need to check OK response and last state of ajax call.
{
window.location.href = 'REDIRECT_URL'
window.location.reload() // To refresh page.
}
};
xhr.open('POST', e.target.action);
xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken'));
//xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(form_data);
}
Now in case of Django you need also need to add view / call proper action that should return either json or xml.
from django.http import JsonResponse
def some_view(request):
return JsonResponse({"key": "value"})
To know how ajax work you can check here https://www.w3schools.com/xml/ajax_intro.asp
Upvotes: 1
Reputation: 1187
1) Ajax request should not receive redirect response. Usually it supposed to be a valid json-string. Django has a JsonResponse for this purpose. If you want your django view to process ajax data you should check it on your backend side, for example:
if request.is_ajax():
return JsonResponse({'data': data})
2) You can do redirect with your javascript code, for instance:
window.location.href = 'https://stackoverflow.com'
Upvotes: 1