A
A
Alexander Vinogradov2019-03-02 15:47:20
Django
Alexander Vinogradov, 2019-03-02 15:47:20

How to make an ajax contact form using JS?

I looked a lot on the net for examples, but everywhere there are some semi-finished products.
There is an example in the documentation .
What do I need:

  • client on pure JS without stupid jQuery (already got this jQ crutch by the fact that almost everywhere there are examples only on it)
  • representation only in the form of classes, not from functions.

What do I have.
The working feedback form is not ajax with a transition to another page.
But I will give a piece of code where I am already trying to remake it.
view.py
from django.views.generic.edit import CreateView
from .models import Contact, Files
from .forms import ContactForm
from django import http
import pdb # pdb.set_trace()


class AjaxableResponseMixin:
    """
    Mixin to add AJAX support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    """
    def form_invalid(self, form):
        response = super().form_invalid(form)
        if self.request.is_ajax():
            return http.JsonResponse(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        response = super().form_valid(form)
        if self.request.is_ajax():
            data = {
                'pk': self.object.pk,
            }
            return http.JsonResponse(data)
        else:
            return response


class ContactView(AjaxableResponseMixin, CreateView):
    model = Contact
    fields = ('name', 'phone', 'email', 'body')


# class ContactView(FormView):
#     form_class = ContactForm
#     template_name = 'contact/contact.html'
#     success_url = '#' # адрес страницы успеха отправки формы


#     def post(self, request, *args, **kwargs):
#         pdb.set_trace()
#         form_class = self.get_form_class()
#         form = self.get_form(form_class)
#         files = request.FILES.getlist('files')
#         if form.is_valid():
#             id = form.save().pk
#             contact = Contact.objects.get(pk=id)
#             if files:
#                 for f in files:
#                     fl = Files(contact=contact, file = f)
#                     fl.save()
#             data = {'message': 'Сообщение успешно отправлено.'}
#             return http.JsonResponse(data)                 #self.form_valid(form)
#         else:
#             return self.form_invalid(form)


class ContactSent(CreateView):
    pass

JS
function ajaxPOST(url, callback) {
  var request = new XMLHttpRequest();

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      callback(request.responseText);
    }
  };

  request.open("POST", url, true);
  request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  request.send();
}

function send(obj) {
  url = obj.action;
  ajaxPOST(url, function(data) {
    alert(data);
  });
  return false;
}

index
<form class="tile contact" action="{% url 'contact_form' %}" method="POST" onsubmit="send(this)" enctype="multipart/form-data">
  {% csrf_token %}
<p> <input type="text" name="name" placeholder="Ваше имя" maxlength="50" class="form-control" id="id_name"></p>
<p> <input type="text" name="phone" placeholder="Номер телефона. Обязательно" maxlength="50" class="form-control" required id="id_phone"></p>
<p> <input type="text" name="email" placeholder="email" maxlength="50" class="form-control" id="id_email"></p>
<p> <textarea name="body" cols="40" rows="10" placeholder="Текст сообщения. Обязательно" class="form-control" required id="id_body">
</textarea></p>
<p> <input type="file" name="files" multiple class="form-control" id="id_files"></p>
  <button class="btn" type="submit">Отправить</button>
</form>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question