Login

save form in ajax with jquery in django

Author:
ralphleyga
Posted:
August 24, 2010
Language:
Python
Version:
1.3
Score:
2 (after 8 ratings)

Code how to save ajax.in a form

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#views.py
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, Http404
from django.template.loader import get_template
from django.template import RequestContext
from django.template import Context
from django.utils import simplejson

from forms import MyForm

def ajax_view(request):
    """
    handles the ajax
    """
    template = 'mytemplate/page.html'

    if request.is_ajax():
		if request.method == 'POST':
		    post = request.POST
		    my_form = MyForm(request.POST)
		    if my_form.is_valid():
		        new = my_form.save(commit=True)
		        response = {
		                            'status':True,
		                        }
		    else:
		        response = {
		                            'status':False
		                        }
		    json = simplejson.dumps(response, ensure_ascii=False)
		    return HttpResponse(json, mimetype="application/json")
		
		context = {'my_form':my_form}
		return render_to_response(template, context, context_instance=RequestContext(request))
	else:
		raise Http404


#urls.py
from django.conf.urls.defaults import *

from views import ajax_view

urlpatterns = patterns('', 
    url(r'^$', ajax_view, name="ajax_view"),
)

#page.html

<script type="text/javascript"  src="{{ MEDIA_URL }}js/lib-common/jquery-1.4.2.min.js"></script>
<script type="text/javascript"  src="{{ MEDIA_URL }}js/lib-common/jquery.form.js"></script>

<form action="" method="post" id="myform">
{{ myform.as_p }}
<input type="submit" name="submit" value="SUBMIT" id="submit" />
</form>

<script type="text/javascript">
$(document).ready(
    function() 
    {
	    $('#myform').ajaxForm({
		        beforeSubmit: function(arr, $form, options) {
                        var field=$('#field').val();
                        if (field!=null) {
                            $('#my_form').ajaxStart( function() {
                                    alert('loading');
                                });
                            return true;
				        }
				        else
				        {
                            alert
                            return false;
				        }
			        },	
		        success: function(response) {                    }
		        });
    }
    );
</script>

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

mwdiers (on August 25, 2010):

You have cruft left over from whatever project you extracted this from.

Line 20: my_form = BetaUserForm(request.POST)

should be deleted.

Line 21 should read:

if my_form.is_valid():

Line 64:

$('#id_beta_user_form') should read $('#id_my_form')

And finally, your view should at least be checking that the request is actually an ajax request, Line 18:

if request.method == 'POST' and request.is_ajax():

#

Please login first before commenting.