I am looking to incorporate ajax into my invitation form. The form is quite simple, involving the submission of an email address. I have successfully implemented ajax in the form, but I am encountering a problem with displaying Django-specific errors. For instance, when attempting to submit the same email address, it should trigger an error message stating:
This email already exists
Additionally, if I provide the email as "abcd@gmail", my ajax code indicates success. How can I validate for such conditions when using ajax?
$('.invitation-form').on('submit', function(event){
event.preventDefault(); // preventing the default browser behavior for form submission
console.log('event', event.target);
requestInvitation();
})
function requestInvitation(){
console.log('request');
console.log($('.requested_email').val());
$.ajax({
url: '/invitations/request/',
type: 'POST',
data: {email: $('.requested_email').val(), csrfmiddlewaretoken: '{{ csrf_token }}'},
success: function(data) {
$('.requested_email').text('');
$('.display').html("<div class='ui floating message'>Success</div>")
console.log('data', data);
},
error: function(xhr,errmsg,err){
$('.display').html("<div class='ui floating message'>Oops! We have encountered an error: "+errmsg+"</div>"); // want to show django specific error
}
})
}
@csrf_exempt
def requestInvitation(request):
form = InviteForm(request.POST or None)
response_data = {}
if form.is_valid():
join = form.save(commit=False)
email = form.cleaned_data.get('email')
already_join, created = Invitation.objects.get_or_create(email=email)
if created:
already_join.invite_code = get_invite_code()
already_join.save()
response_data['result'] = "Thank you for your interest"
response_data['email'] = email
send_request_received_email.delay(email,already_join.email_tracker)
return HttpResponse(json.dumps(response_data),content_type="application/json")
# return HttpResponseRedirect('/')
context = {"form": form}
return render(request, 'invitation/invitation.html', context)
HTML
<form method="POST" class="invitation-form vcenter">
{% csrf_token %}
<div class="ui action input">
<input type="email" class="requested_email" name="email" placeholder="Email address">
<button class="ui button primary">Request Invite</button>
</div>
</form>