1

I have a Django form on one of the pages which I am trying to submit using Jquery-Ajax.

Following is my code:

I have used Jinja templating to render the form on page.

 <form action='' method='post' name='ContactForm' id='ContactForm'> 
                        {% csrf_token %}
                            {% for field in form %}
                                <div class="input-group"> <span class="input-group-addon">@</span>
                                   {{ field }}
                                </div>
                            {% endfor %}
                            <div class="input-group form-buttons"> <span class="input-group-btn">
                                <button class="btn btn-default" type='submit' value='Submit' name='submitf' id="submitf">SAY HELLO</button>
                                </span> 
                            </div>
                            <div id='message_post'></div>
 </form>
 <script type="text/javascript" src="{% static 'personal/js/contact/contact-form.js' %}"></script> 

contact-form.js

$(function(){
$("#ContactForm").submit(function(){
    $("#submitf").value='Please wait...';
    alert("Control reached the script.");
    $.post("/contact/add/", $("#ContactForm").serialize(),
    function(data){ 
        alert("Alert entered function.");
        if(data.status == 'error'){ 
                $("#message_post").html("<div class='errorMessage'>ERROR: " + data.msg + "!</div>"); 
                document.ContactForm.submitf.value='Resend >>';
                document.ContactForm.submitf.disabled=false;
        } else {
            $("#message_post").html("<div class='successMessage'>Hi! Glad to meet you. I'll definitely contact you shortly.</div>"); 
            $("#submitf").value='Send >>';
            }
    }, "json");
    return false;   
});
});

urls.py

from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^contact/add/$', views.add, name='add')
]

views.py

def add(request):
    if request.method=='POST' and request.is_ajax():
        form=ContactForm(request.POST)
        if form.is_valid():
            try:
                form.save()

            except Exception as e:
                print ('%s' % str(e))
                msg = 'That\'s embarrassing. Will you please Say Hello again?'
                status = "Error"

            else:
                msg = 'Connected'
                status = "Success"

        print('status %s' % status)
        request.write({'message':msg, 'status':status})

But everytime I hit the submit button it gives the following error:

POST /contact/add/ HTTP/1.1" 404 2043

What I intend to do is when button is clicked the data in the form should be inserted into the database.

Referred following links and SO question but couldn't resolve the problem:

How to POST a django form with AJAX & jQuery

Django Project Docs

submitting a django form using javascript

Currently in learning phase of Python and Django. Highly appreciate any help.

Community
  • 1
  • 1
Codenaldo
  • 11
  • 2
  • You can try to use Postman if you want to check the API endpoint, to make sure the error isn't server-sided – Randy Dec 29 '16 at 13:12
  • @Randy Postman is probably for email services and AWS which neither I am using in my simple application. I might be wrong in interpreting your suggestion. If you could explain a bit in detail. – Codenaldo Dec 29 '16 at 13:19
  • Actually, Postman is a very easy solution to make any call (POST, GET etc.) with relevant data to any API. That way you can make sure the error is in the request or in the back-end and that way you know where to start debugging – Randy Dec 29 '16 at 13:22

1 Answers1

1

Could you provide the view just to check it?

Although, check the documentation on making use of CSRF together with ajax: https://docs.djangoproject.com/en/1.10/ref/csrf/

You may need to add some AJAX settings before. I am providing to you a small gist that can help you: https://gist.github.com/silviomoreto/485b6a294b40f06011946d8be09c6e1f

silviomoreto
  • 5,629
  • 3
  • 30
  • 41