Login Ajax form not working, redirecting to another page

I have created a Ajax form to handle the errors in my login form, but instead of showing errors in the form area, it directs me to another page with the json error response

<div class="container-fluid bg-primary" id="login">
    <div class="row">
        <div class="col-lg-3 text-center">
        <div class="col-lg-6 text-center">
            <h2 class="section-heading">Login to your profile</h2>
        <div class="col-lg-3 text-center">
    <div class="col-md-4 col-md-offset-4 ">
        <form id='loginform' action='/users/login/' method='post' accept-charset='UTF-8'>
        {% csrf_token %}
            <fieldset >
                <div class="form-group">
                    <input type="text" name="mobile_number" id="mobile_number" tabindex="1" class="form-control" placeholder="Mobile Number" value="">
                <div class="form-group">
                    <input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Enter Password">
            <button type="submit" class="btn btn-primary btn-xl btn-block">LOG IN</button><br><br>
            <span class="login-error"></span>

My ajax code

$("#loginform").on('submit', function(event) {
        alert("Was preventDefault() called: " + event.isDefaultPrevented());
        console.log("form submitted!");
        var url = "/users/login-ajax/";

            type: "POST",
            data: $("#loginform").serialize(),
            success: function(data)
                var result = JSON.stringify(data);
                if(result.indexOf('errors')!=-1 ){
                    if(data.errors[0] == "Mobile number and password don't match")
                        $('.login-error').text("Mobile number and password don't match");

                    else if(data.errors[0] == "Entered mobile number is not registered")
                        $('.login-error').text("Entered mobile number is not registered");


                //var result = JSON.stringify(data);
                // console.log(result);


My code for the action in views.py

def login(request):
if request.method == 'POST':
    mobile_number = request.POST.get('mobile_number', '')
    password = request.POST.get('password', '')

    data = {}

    user_queryset = User.objects.filter(mobile_number=mobile_number)

    if len(user_queryset) == 0:
        data['error'] = []
        data['error'].append("Entered mobile number is not registered")
        # return JsonResponse(data)

    elif len(user_queryset) == 1:
        email = user_queryset[0].email

        user = auth.authenticate(email=email, password=password)

        if user is not None:
            auth.login(request, user)

            data['error'] = []
            data['error'].append("Mobile number and password don't match")

    return JsonResponse(data)

Source: ajax

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.