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 email address is added. There is no response and firebug shows "500 Internal Server Error" What am I doing wrong ?