POST with AJAX (Fetch)
<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>

 

 

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



09 Sept. 2024 | Last Updated: 02 Dec. 2025 | jaimedcsilva

Related
  • GET (Query Parameters)
  • GET (URL Parameters)
  • GET with AJAX (Fetch)
  • POST
  • POST with AJAX (Fetch)

  • Buy Me a Coffee