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>
        <div class="col-lg-6 text-center">
        <h1>&nbsp;</h1><h3>&nbsp;</h3>
            <h2 class="section-heading">Login to your profile</h2>
            <hr>
        </div>
        <div class="col-lg-3 text-center">
        </div>
        <h2>&nbsp;</h2>
        <h2>&nbsp;</h2>
        <h2>&nbsp;</h2>
    </div>
    <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>
                <div class="form-group">
                    <input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Enter Password">
                    </div>
            </fieldset>
            <button type="submit" class="btn btn-primary btn-xl btn-block">LOG IN</button><br><br>
            <span class="login-error"></span>
            <h1>&nbsp;</h1><h1>&nbsp;</h1>
        </form>
    </div>

My ajax code

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

        $.ajax({
            type: "POST",
            url:url,
            data: $("#loginform").serialize(),
            success: function(data)
            {
                console.log(data);
                var result = JSON.stringify(data);
                if(result.indexOf('errors')!=-1 ){
                    console.log(data);
                    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");
                    }
                }

                else
                {
                    window.open("/users/profile/");
                }

                //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)

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

    return JsonResponse(data)


Source: ajax

Leave a Reply