Django form submit without refreshing

  ajax, django, forms, json, python

thanks in advance. I know this has been asked a few times. But after reading the previous questions, reading and understanding JSON and AJAX forms tutorials, I still can’t find a way to not having the website refreshed after submitting a form. I would really appreciate it if any of you with a higher knowledge of JavaScript is able to give a hand.

This is a newsletter at the bottom part of the Home page that just asks for a name and an email and it keeps the information in the database, it works perfect and I just would like to reply with a confirmation message without refreshing, because it replies a message but the user has to go to the bottom of the page again to see it which is not practical at all.

The HTML is

<div id="contact_form">
                                            <div class="Newsletter">                                                        
                                                 <form id="form" enctype="multipart/form-data" method="POST" action="" style="text-align: left;">
                                                    {% csrf_token %}
                                                    <div class="fields">
                                                         <div class="fields">
                                                    <label for="name" id="name_label">Name</label>
                                                    <input type="text" name="name" minlength="3" placeholder="e.g. John Smith" id="name" required>
                                                        </div>
                                                        <div class="fields">
                                                    <label for="email" id="email_label">Email</label>
                                                    <input type="email" name="email" placeholder="e.g. [email protected]" id="email"  required>
                                                        </div>
                                                        
                                                        
                                                    </div>
                                                <div class="submit">
                                                <button type='submit' id="submit" >Subscribe</button>
                                               </div>   
                                               {% include 'messages.html' %}
                                                </form>
                                            </div>
                                        </div>

The index view

def index(request):
    """View function for home page of site."""
    if request.method == 'POST':
        form = NewsUserForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False) #we do not want to save just yet    
            if NewsUsers.objects.filter(email=instance.email).exists():
                messages.warning(request, 'Your email already exists in the newsletter database')
            else: 
                instance.save()
                messages.success(request, 'Great! Your email has been submitted to our database.')  
                try:
                    send_mail('Welcome ', 'Thank you for subscribing to the Newsletter. ', '[email protected]',[instance.email], fail_silently=False)                 
                except BadHeaderError: #add this
                    return HttpResponse('Invalid header found.') #add this  
    form = NewsUserForm()
    return render(request, 'index.html', {'form':form})

Most of the tutorials suggest to create another view + an url for that view + ajax code

I tried this one from here (https://pytutorial.com/how-to-submit-a-form-with-django-and-ajax#top) without success, also eliminating "post" in html method but still not working, even the info got from the form appears in the url. Any help will be welcome, thank you very much.

jquery unsuccessful code

    $('#form').on('submit', function(e){
             
         e.preventDefault();
         

         
           $.ajax({
                type : "POST", 
                url: "{% url 'index' %}",
                data: {
                 name : $('name').val(),
                 email : $('email').val(),
                 csrfmiddlewaretoken: '{{ csrf_token }}',
                 dataType: "json",
         
                },
                
                success: function(data){
                   $('#output').html(data.msg) /* response message */
                },
         
                failure: function() {
                    
                }
         
         
            });
         
         
         });    

unsuccessful ajax view function and url

def ajax_posting(request):
    if request.is_ajax():
        name = request.POST.get('name', None) # getting data from first_name input 
        email = request.POST.get('email', None)  # getting data from last_name input
        if name and email: #cheking if first_name and last_name have value
            response = {
                         'msg':'Your form has been submitted successfully' # response message
            }
            return JsonResponse(response) # return response as JSON

#path('ajax-posting/', views.ajax_posting, name='index'),# ajax-posting / name = that we will use in ajax url

Source: Python Questions

LEAVE A COMMENT