Need a simple working ajax example for django forms

14,338

Solution 1

OK..thx for your comments..I got it all sorted out..basically I just missed out on the {% csrf_token %} and csrfmiddlewaretoken:'{{ csrf_token }}'..just for the benefit of those who might be reading this..the new codes will look something like this

the javascript:

<script type="text/javascript">
$(document).ready(function(){

  $("#my_form").submit(function(){
    $.post("",
    {name:"Donald Duck",
     city:"Duckburg",
     csrfmiddlewaretoken:'{{ csrf_token }}'
     },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    })
    .fail(function(xhr) {
        console.log("Error: " + xhr.statusText);
        alert("Error: " + xhr.statusText);
    });
    return false;
  });

});
</script>

the html:

<form id="my_form" action="" method="post">{% csrf_token %}
<input type="submit" value="Send">
</form>

Solution 2

Check this example: Check this Link

Models

class Color(models.Model):
    color = models.CharField(max_length=256)

class Auto(models.Model):
    type = models.CharField('auto type', max_length=256)
    colors = models.ManyToManyField(Color) 

from django import forms
from models import Color, Auto

    class AutoForm(forms.Form):
        TYPE_CHOICES = [('', '-- choose a type --'), ] + [(t.type, t.type) for t in Auto.objects.all()]
        COLOR_CHOICES = [(c.color, c.color) for c in Color.objects.all()]
        COLOR_CHOICES.insert(0, ('', '-- choose a vehicle type first --'))

        type = forms.ChoiceField(choices=TYPE_CHOICES, widget=forms.Select(attrs={'onchange':'get_vehicle_color();'}))
        color = forms.ChoiceField(choices=COLOR_CHOICES)
    [Check this article][2] can be helpful

Templates

{% extends "base.html" %}
{% block head %}
<script type="text/javascript" src="/site_media/prototype.js"></script>
<script type="text/javascript" src="/site_media/my_ajax_function.js"></script>
{% endblock %}

{% block content %}
    {% if form_was_valid %}
        {# ... show whatever... #}
    {% else %}
        <form action="/auto/reserve/" method="POST">
        <ul>
        {{ form.as_ul}}
        <li><label for="submit">&nbsp;</label>
        <input type="submit" id="submit" name="submit" value="Submit"/></li>
        </ul>
        </form>
    {% endif %}
{% endblock %}

Javascript

function get_vehicle_color(){
    new Ajax.Request('/auto/ajax_purpose_staff/', { 
    method: 'post',
    parameters: $H({'type':$('id_type').getValue()}),
    onSuccess: function(transport) {
        var e = $('id_color')
        if(transport.responseText)
            e.update(transport.responseText)
    }
    }); // end new Ajax.Request
}

URL.py

urlpatterns = patterns('mysite.auto.views',
    (r'^ajax_color_request/$', 'ajax_color_request'),
    # ... everything else...
)


def ajax_color_request(request):
    # Expect an auto 'type' to be passed in via Ajax and POST
    if request.is_ajax() and request.method == 'POST
        auto_type = Auto.objects.filter(type=request.POST.get('type', ''))
        colors = auto_type.colors.all() # get all the colors for this type of auto.
    return render_to_response('auto/ajax_color_request.html', locals())

{% for c in colors %}
    <option value="{{ c.color }}">{{ c.color|title }}</option>
{% endfor %}
Share:
14,338

Related videos on Youtube

Allan Eswar
Author by

Allan Eswar

Updated on June 04, 2022

Comments

  • Allan Eswar
    Allan Eswar almost 2 years

    Basically I need something similar to http://www.w3schools.com/jquery/jquery_ajax_get_post.asp done in django. I've downloaded the samples and tested it locally with a localhost + php and it works out fine but I can't seem to get it to work in django no matter how simple the example is. Here's basically what I've done based on the example from the link above with slight modification

    the javascript:

    <script type="text/javascript">
    $(document).ready(function(){
      $("#my_form").submit(function(){
        $.post("",
        {name:"Donald Duck",
         city:"Duckburg"},
        function(data,status){
          alert("Data: " + data + "\nStatus: " + status);
        })
        .fail(function() { alert("error"); });
        return false;
      });
    });
    </script>
    

    the urls:

    url(r'^ajax/$', views.ajax_test, name="ajax"),
    

    the views:

    def ajax_test(request):
        if request.method == 'POST' and request.is_ajax():
            name = request.POST['name']
            city = request.POST['city']
            message = name + ' lives in ' + city
    
            return HttpResponse(json.dumps({'message': message})) #tried without the json. Doesn't work either
    
        return render(request, 'books/ajaxTest.html')
    

    the html:

    <form id="my_form" action="" method="post" {% if form.is_multipart %}enctype="multipart/form-data"{% endif %}>{% csrf_token %}
    <input type="submit" value="Send">
    </form>
    

    The form is suppose to include a django form but since I can't even get the basics to work, that would be kinda pointless. Someone mentioned about the csrf_token tag but removing that doesn't solve the problem either. The output of the above example basically just yields the alert('error') and nothing else. I've been through so many examples but I can't even get the most basic ones to work

  • Paul
    Paul over 10 years
    Nice. Thanks for posting that.