skip to Main Content

I’ve tried looking up online, rewriting the code but the submit() won’t fire but when I use a click event, it fire an calls the callback and the ajax() runs. I cannot figure out what’s really wrong with the code even after going through so many tutorials and documentation online.

Here’s the code:

  1. HTML template with the form
{% load static %}

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Login</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <!-- site icon -->
    <link rel="icon" href="{% static 'img/question.png' %}">
    <!-- Bootstrap core CSS -->
    <link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">

    <!-- Font Awesome -->
    <link href="{% static 'css/font-awesome.min.css' %}" rel="stylesheet">

    <!-- Endless -->
    <link href="{% static 'css/endless.min.css' %}" rel="stylesheet">
  </head>

  <body>
    <div class="login-wrapper">
        <div class="text-center">
            <span>
                <img src="{% static 'img/question.png' %}" style="height: 100px; width: 100px; border-radius: 50%;">
            </span>
        </div>
        <div class="text-center">
            <h2 class="fadeInUp animation-delay8" style="font-weight:bold">
                <span class="text-success">CitiSpy User Login</span>
            </h2>
        </div>
        <div class="login-widget animation-delay1"> 
            <div class="panel panel-default">
                <div class="panel-heading clearfix">
                    <div class="pull-left">
                        <i class="fa fa-lock fa-lg"></i> Login
                    </div>
                </div>
                <div class="panel-body">
                    <div id="login-form-main-message"></div>
                    <form class="form-login" id="login_form" method="POST">
                        {% csrf_token %}
                        <div id="form_content">
                            {{ form.non_field_errors }}
                            <div class="form-group">
                                {{ form.email.errors }}
                                <label for="{{ form.email.id_for_label }}">{{ form.email.label }}</label>
                                {{ form.email }}
                            </div>
                            <div class="form-group">
                                {{ form.password.errors }}
                                <label for="{{ form.password.id_for_label }}">{{ form.password.label }}</label>
                                {{ form.password }}
                            </div>        
                            <div class="seperator"></div>
                            <hr/>
                            <div class="form-group">
                                <!-- <button class="btn btn-success btn-sm bounceIn animation-delay5 login-link pull-right" type="submit" id="id_submit">
                                    <i class="fa fa-sign-in"></i>
                                     Login
                                </button> -->

                                <a type="submit" class="btn btn-success btn-sm bounceIn animation-delay5 login-link pull-right" id="login_submit" href="#"> -->
                                    <i class="fa fa-sign-in"></i>
                                     Login
                                </a> 
                            </div>     
                        </div>  
                    </form>
                </div>
            </div><!-- /panel -->
        </div><!-- /login-widget -->
    </div><!-- /login-wrapper -->
    <!-- Jquery -->
    <script src="{% static 'js/jquery-1.10.2.min.js' %}"></script>

    <!-- Bootstrap -->
    <script src="{% static 'bootstrap/js/bootstrap.js' %}"></script>

    <!-- Pace -->
    <script src="{% static 'js/uncompressed/pace.js' %}"></script>

    <!-- Popup Overlay -->
    <script src="{% static 'js/jquery.popupoverlay.min.js' %}"></script>

    <!-- Slimscroll -->
    <script src="{% static 'js/jquery.slimscroll.min.js' %}"></script>

    <!-- Modernizr -->
    <script src="{% static 'js/modernizr.min.js' %}"></script>

    <!-- Cookie -->
    <script src="{% static 'js/jquery.cookie.min.js' %}"></script>

    <!-- Endless -->
    <script src="{% static 'js/endless/endless.js' %}"></script>

    <!--login js-->
    <script src="{% static 'js/accounts/login_1.js' %}"></script>
  </body>
</html>

  1. JavaScript
$(document).ready(function(){
    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;
    }

    var $csrf_token = {
        name: "csrfmiddlewaretoken",
        value: getCookie('csrftoken')
    };
    var $myId = $("#login_form >#form_content > .form-group > button").attr('class');
    console.log($myId);
    $("#login_form").submit(function(event){
        console.log("I am in submit");
        event.preventDefault();
        var $form_data = $(this).serializeArray();
        $form_data.push($csrf_token);

        $.ajax({
            type: 'POST',
            data: $form_data,
            cache: false,
            dataType: 'json',
            url: '/accounts/userLogin/',
            beforeSend: function(){
                $("#login-form-main-message").css("display", "block").html("<div class='alert alert-info'><img height="24px;" src="{% static '/images/double-ring.gif' %}" alt="loading" />  Please wait...</div>");
                $("#form_content").css("display", "none");
            },
            success: function(data){
                if (data.status === "ok"){
                    if (data.to === "verify") {
                        //redirect to account verification
                    } else {
                        if (data.to === "user") {
                            //redirect to user account
                            $("#login-form-main-message").css("display", "block").html("<div class='alert alert-info'><img height="24px;" src="{% static '/images/double-ring.gif' %}" alt="loading" /> Success! login you in, please wait...</div>");
                            $("#form_content").css("display", "none");
                        }else{
                            $("#login-form-main-message").css("display", "block").html("<div class='alert alert-info'><img height="24px;" src="{% static '/images/double-ring.gif' %}" alt="loading" /> Success! login you in, please wait...</div>");
                            $("#form_content").css("display", "none");
                            location.href = '/em_dept/dashboard/';
                        }
                    }
                }
            },
            error:function(xhr,errmsg,err){
                console.log("error error error!!!");
                console.log(xhr.status + ": " + xhr.responseText);
            }
        });
        // return false;
    });
});
  1. The View rendering the form
@method_decorator(csrf_protect, name='post')
class UserLogin(LoginView):
    """docstring for UserLogin"""
    template_name = 'accounts/login.html'
    # authentication_form = LoginForm()

    def get(self, request):
        '''a func to work on the request.POST'''
        print("getting the form for you ")
        form = LoginForm()
        return render(request,self.template_name,{'form':form})

    def post(self, request):
        form = LoginForm(request.POST)
        print("go the data for you")
        if request.is_ajax():
            print("entered form")
            if form.is_valid():
                print("form valid")
                email = form.cleaned_data['email']
                try:
                    user = User.objects.get(email=email)
                    print("user obj", user)
                    if user.check_password(form.cleaned_data['password']):
                        # 0-super admin, 1-dept admin,2-dept staff, 3-end user 
                        print("correct password")
                        if user.account_type == 4:
                            if user.last_login == None or user.last_login == '':
                                to = "verify"
                            else:
                                to = "user"
                        else:
                            if user.account_type == 2:
                                to = 'dept_admin'
                            elif user.account_type == 3:
                                to = 'dept_staff'
                            elif user.account_type == 1:
                                to = 'super_user'
                            else:
                                to = None
                        res = {'status':'ok', 'error':False, 'acc_type':to, 'data':user.email}
                    else:
                        print("incorrect password")
                        res = {'status':'fail', 'error':'incorrect password'}
                except Exception as e:
                    print("User not found!", e)
                    res = {'status':'fail', 'error':'account not found'}
            else:
                print("form valid")
                res = {'status':'fail', 'error':form.errors}
        return JsonResponse(res)

2

Answers


  1. try to use on('submit') instead of submit().

    What version of jquery do you use ?

    it should be <Input type='submit'not<a>thats why your click worked before…

    Login or Signup to reply.
  2. <a type="---" is just a type hinting having submit there does not trigger form submit.

    Why is the actual submit button commented out?

     <!-- <button class="btn btn-success btn-sm bounceIn animation-delay5 login-link pull-right" type="submit" id="id_submit">
                                        <i class="fa fa-sign-in"></i>
                                         Login
                                    </button> -->```
    
    I would uncomment this and go from there.
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search