I've been trying to build an E-mail validator with Django and Javascript/Ajax, but I'm stuck. I get the Ajax response
{response: "This field is required.", email: false}
email: false
response: "This field is required."
But it's always the same, even if I fill in the E-mail field.
This is my view.py
@requires_csrf_token
def email_check(request):
email = request.POST.get('email', False)
if request.is_ajax():
if email:
query_email = CustomUser.objects.filter(email=email)
if query_email.exists():
res = "{0} is already in use.".format(email)
else:
res = "This E-mail is ok."
ajax_vars = {'response': res, 'email': email}
json_data = json.dumps(ajax_vars)
else:
res = "This field is required."
ajax_vars = {'response': res, 'email': email}
json_data = json.dumps(ajax_vars)
return HttpResponse(json_data, content_type='application/json')
This is the template and the script
<form>
{% csrf_token %}
<input id="email" type="email" name="email">E-mail</a>
</form>
<script type="text/javascript">
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
$(document).ready(function() {
$("#email").focusout(function(e) {
e.preventDefault();
var csrftoken = getCookie('csrftoken');
var email = $('#email').val();
$.ajax({
url: "/email_check/",
type: "POST",
dataType: "json",
contentType: "application/json",
data : {
csrfmiddlewaretoken: csrftoken,
email: email
},
success: function(result) {
console.log(result);
},
});
});
});
</script>
I'm probably skipping some steps, can you help me understand which they are?
Thanks!
Remove the following args from $.ajax()
dataType: "json",
contentType: "application/json",
And it'll work.
I tested it locally, when content type is application/json
it doesn't seem to work as expected. Maybe django expects the content type to be application/x-www-form-urlencoded
for a POST request.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.