blog_django_logo.png

Sending form data (POST) with fetch api in Django

Django Javascript

Do you want to post a Django form without the page reloading?

Don't want another (jQuery) dependency?

Just want to use up to date JavaScript?

Great this post is for you

# Form

        <form id="contact-form" method="post">
    {% csrf_token %}
    {{ form|crispy }}
    <div class="form-actions">
        <button type="submit">Send Enquiry</button>
    </div>
</form>
    

# Javascript

        document.querySelector('#contact-form').addEventListener('submit', postData);

function postData(event){
    event.preventDefault();

    let id_name = document.getElementById('id_name').value;
    let id_email = document.getElementById('id_email').value;
    let id_subject = document.getElementById('id_subject').value;
    let id_message = document.getElementById('id_message').value;

    let dataForm = new FormData();
    
    dataForm.append('name', id_name);
    dataForm.append('email', id_email);
    dataForm.append('subject', id_subject);
    dataForm.append('message', id_message);
    dataForm.append('csrfmiddlewaretoken', '{{ csrf_token }}');

    fetch('{% url "sendemail:contact" %}', {
        method: 'post',
        body: dataForm,
    })
    .then((result) => {
        console.log('Success:', result);
        let banner = document.querySelector('.success-banner')
        banner.style.display = 'block';
    })
}
    

The key to success with this post which is missing from my other failed google searches is to use FormData() instead of JSON.stringify().

Read more about FormData on MDN web docs