I'm trying to add ajax form submit to my webpage. Form will add user's email to newsletter. I've found this solution : http://www.tutorialswitch.com/web-development/quick-and-simple-ajax-forms-with-json-responses/ and now I'm trying to rewrite it for django.
So I have my form, included on main page :
<div id="form-newsletter-message"></div>
<form action="{% url newsletter_add %}" method="post" class="form-newsletter" id="form-newsletter">
<input type="text" class="form-text" name="email" />
<input type="submit" value="Add" class="form-submit" />
</form>
Here's my application.js, only change is the name of the form :
function setupAjaxForm(form_id, form_validations){
var form = '#' + form_id;
var form_message = form + '-message';
var disableSubmit = function(val){
$(form + ' input[type=submit]').attr('disabled', val);
};
$(form).ajaxSend(function(){
$(form_message).removeClass().addClass('loading').html('Loading...').fadeIn();
});
var options = {
dataType: 'json',
beforeSubmit: function(){
if(typeof form_validations == "function" && !form_validations()) {
return false;
}
disableSubmit(true);
},
success: function(json){
$(form_message).hide();
$(form_message).removeClass().addClass(json.type).html(json.message).fadeIn('slow');
disableSubmit(false);
if(json.type == 'success')
$(form).clearForm();
}
};
$(form).ajaxForm(options);
}
$(document).ready(function() {
new setupAjaxForm('form-newsletter');
});
URL :
urlpatterns = patterns('',
url(r'^newsletter_add/$', 'views.newsletter_add', name="newsletter_add"),
)
And now the problem is with the view. Basing on the sample .php function, I've created this :
if request.method == "POST":
try:
e = NewsletterEmails.objects.get(email = request.POST['email'])
message = _(u"Email already added.")
type = "success"
except NewsletterEmails.DoesNotExist:
logging.debug("nie dodany")
try:
e = NewsletterEmails(email = request.POST['email'])
except DoesNotExist:
pass
message = _(u"Email added successfully.")
type = "success"
e.save()
Result of this is when I click submit button, I get the 'Loading..." text and then nothing. Submit button is constantly disabled (until I restart browser) but my emai开发者_如何学Cl address is added. There is no response and firebug shows "500 Internal Server Error" What am I doing wrong ?
just as an idea, I've had similar problem some time ago : http://code.djangoproject.com/ticket/5868
Your first step here is to see what's happening with the Ajax request. I recommend Firefox with the Firebug addon for debugging Ajax issues, even though I use Chrome for regular browsing. Enable the console tab in Firebug, and refresh your page. The Ajax request should show up there, and you can expand it and see if there was an error page returned. With Firebug, you can view the error page that was returned and figure out what went wrong.
精彩评论