pemistahl
pemistahl

Reputation: 9584

What is wrong in my Django & jQuery AJAX form submission setup?

I know, you have read questions like this a thousand times or even more often, and I have also read these questions and their answers, but I simply cannot get my AJAX form to work correctly using jQuery on the client side and Django on the server side. Also, I was not able to find a stupid simple step-by-step tutorial for a Python guy and JavaScript newbie like me which is understandable and detailed enough to give me the aha moment that I'm so eagerly waiting for.

I have a form on a HTML page and when clicking the submit button, the respective HttpResponse should simply be alerted using JavaScript's alert() function, but it doesn't work. When I submit the form, I find the following entry in Django's development server console:

"POST /ajaxtest/%5Bobject%20Object%5D HTTP/1.1" 404 2381

Please tell me what's wrong with my code. Thank you very much in advance!

forms.py

from django.db import forms

class AjaxTestForm(forms.Form):
    first_name = forms.CharField()
    last_name = forms.CharField()

views.py

from django.http import HttpResponse
from django.shortcuts import render
from my_app.forms import AjaxTestForm

def ajax_test(request):
    if request.is_ajax() and request.method == 'POST':
        form = AjaxTestForm(request.POST)
        if form.is_valid():
            print request.POST
            # I want this to be alerted
            return HttpResponse('Your AJAX form test was successful!')
        else:
            return HttpResponse('Your AJAX form test failed miserably!')
    else:
        form = AjaxTestForm()

    return render(request, 'ajaxtest.html', {'form': form})

urls.py

from django.conf.urls import patterns, url
from my_app.views import ajax_test

urlpatterns = patterns('',
    url(r'^ajaxtest/$', ajax_test, name='ajax-test-page')
)

ajaxtest.html

<!DOCTYPE html>
<html>
<head>
    <script src="{{ STATIC_URL }}js/jquery-1.8.2.min.js"></script>

    <script>

        $(document).ready(function() {

            $('#ajaxform').submit(function(event) {

                var $form = $(this);
                var serializedData = $form.serialize();

                $.post({
                    url: '/ajaxtest/',
                    data: serializedData,
                    success: function(response) {
                        alert(response);
                    }
                });

                event.preventDefault();

            });
        });

    </script>
</head>

<body>
    <form id="ajaxform" method="post" accept-charset="UTF-8" action="">{% csrf_token %}

        <fieldset>
            {% for field in form %}
                <label for="{{ field.label }}">{{ field.label }}</label>
                <input id="{{ field.label }}" type="text" name="{{ field.html_name }}" />
            {% endfor %}

            <button type="submit">Submit</button>
        </fieldset>

    </form>
</body>
</html> 

Upvotes: 2

Views: 1166

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599628

The clue is in the console: it's showing that it's appending [object Object] to the URL it's POSTing to. I suspect that that's the representation of the whole object that you've passed to the $.post function.

This is because unlike the $.ajax function, $.post doesn't take an object, it takes individual parameters. So your code should be:

$.post('/ajaxtest/', serializedData, function(response) {
   alert(response);
});

Upvotes: 7

Related Questions