In my project, I use AJAX to return a message to the user if a form is invalid without them having to refresh their page.
I make the AJAX call however the outcome is not what is expected:
HTML FORM:
<div id="testDiv">
</div>
AJAX:
$('#signupForm input[type=text]').keyup(function() {
var usernameField = $('#usernameField').val(); // Retrieved from SignUpForm in forms.py, and has id of usernameField
var emailField = $('#emailField').val(); // Retrieved from SignUpForm in forms.py, and has id of emailField
var passwordField = $('#passwordField').val(); // Retrieved from SignUpForm in forms.py, and has id of passwordField
var confirmPasswordField = $('confirmPasswordField').val(); // Retrieved from SignUpForm in forms.py, and has id of confirmPasswordField
$.ajax({
url: '/users/signupval/',
data: {
'usernameField': usernameField,
'emailField': emailField,
'passwordField': passwordField,
'confirmPasswordField': confirmPasswordField,
},
dataType: 'json',
success: function(data) {
$('#testDiv').text(data['message']);
console.log("Worked!")
},
error: function(err) {
console.log(err)
}
})
})
views.py:
def signupval(request):
form = SignUpForm(request.GET)
if form.is_valid():
usernameField = form.cleaned_data.get('usernameField')
emailField = form.cleaned_data.get('emailField')
passwordField = form.cleaned_data.get('passwordField')
confirmPasswordField = form.cleaned_data.get('confirmPasswordField')
if len(usernameField) > 7:
return JsonResponse({'message': 'Username field > 7'})
elif len(emailField) > 5:
return JsonResponse({'message': 'Email field > 7'})
elif len(passwordField) > 6:
return JsonResponse({'message': 'Password field > 7'})
elif len(confirmPasswordField) > 6:
return JsonResponse({'message': 'Password field > 7'})
else:
return JsonResponse({'error': 'Something Failed. Please try again'})
The message property is passed back to AJAX and I want to display the message in the div I have (testDiv), however the div is empty and has no text. I know the success function is being called because in my Javascript console via Chrome, I see the `console.log("Worked!"). Does anybody know the issue of why the message is not being displayed? Thank you.