POST with AJAX Fetch
AJAX allows form data to be sent to the server without reloading the page.
In this example, the form is submitted using the Fetch API, and Django returns a JSON response.
Template example
<form method="POST" id="myForm">
{% csrf_token %}
<input type="text" name="param1">
<input type="text" name="param2">
<input type="submit" value="Submit">
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
const formData = new FormData(this);
fetch('/', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {console.log(data);})
.catch(error => console.error('Error:', error));
});
</script>
Django view
from django.views.generic import TemplateView
from django.http import JsonResponse
class index(TemplateView):
template_name = 'index.html'
def post(self, request, *args, **kwargs):
param1 = request.POST.get('param1', 'default_value1')
param2 = request.POST.get('param2', 'default_value2')
print(param1)
print(param2)
context = {}
context['message'] = "Hello World!"
context['param1'] = param1
context['param2'] = param2
return JsonResponse(context)
Tested with Django 4.2