Login with Django and Ajax does nothing

Viewed 142

Here is my form:

<form action="#" method="post">
    {% csrf_token %}
    <div class="form-group">
        <label for="exampleInputEmail1">Enter Username:</label>
        <input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off">
    </div>
    <div class="form-group">
        <label for="exampleInputEmail1">Enter Password:</label>
        <input type="password" class="form-control" id="password" name="password" placeholder="Password" autocomplete="off">
    </div>
    <button class="btn btn-primary" id = 'login_button'>Login</button>
</form>

And the script:

<script src="{% static 'js/jquery-3.5.1.min.js' %}"></script>
<script>
    var login_button = $('#login_button')

    login_button.click(function(){
        var username = $('#username').val()
        var password = $('#password').val()


        $.ajax({
            url: '{% url 'td_app:do_login' %}',
            type: 'get',
            data: {
                'username': username,
                'password': password
            },
            dataType: 'json',
            success: function (data){
                console.log(data.result)
            }
        }).done(function (){
            console.log(data.result)
        })
    })
</script>

In my views.py:

def do_login(request):
    username = request.GET.get('username')
    password = request.GET.get('password')

    user = authenticate(username=username, password=password)
    data = {}

    if user:
        if user.is_active:
            login(request, user)
            data['result'] = 'success'
            return HttpResponseRedirect(reverse('td_app:index'))

    else:
        data['result'] = 'failed'

return JsonResponse(data)

And finally my urls.py:

url(r'^api/do_login/$', views.do_login, name='do_login')

However all of these doesn't work and it doesn't even give me any errors. It just completely refreshes the whole page and does nothing. I tried putting alerts but on the success and done section but it doesn't show it up.

Any thoughts/advices? Thanks a lot!

UPDATE

I tried putting a print on my views.py:

def do_login(request):
    print('A login was attempted!')

    username = request.GET.get('username')
    password = request.GET.get('password')

But when my login executes from the ajax, the print isn't called. It's not giving me any errors too like 'a connection to your view is invalid etc'.

UPDATE 2

I tried changing my jquery script (thanks to @AlwaysHelping):

login_button.click(function(event){
        event.preventDefault()
        var username = $('#username').val()
        var password = $('#password').val()


        $.ajax({
            url: '{% url 'td_app:do_login' %}',
            type: 'POST',
            data: {
                'username': username,
                'password': password
            },
            dataType: 'json',
            success: function (data){
                alert('asdasdas')
            },
            error: function(data){
                alert('there was an error')
            }
        })

I changed the type: 'get' to type: 'POST' and also added an error section. Now when I click the button it gives me the error alert, and when I check the network console it says POST http://127.0.0.1:8000/app/api/do_login/ 403 (Forbidden)

1 Answers

Firstly, you need to use preventDefault method stop the page form reloading each time using e.preventDefault() in your click function.

event.preventDefault()

Secondly, you have a get request in your in your ajax but you are doing a POST instead so change that to POST to send values to django views.

type: POST

Lastly, you do not need an .done method in your ajax since you are using success function which should be enough.

Related