Ismael
Ismael

Reputation: 340

AJAX Form request not sent to Express web server

I'm starting to learn about Expressjs, Twitter Bootstrap and BackBonejs. I have created the basic Expressjs app with the command line tool and added an index.html for the sign in form. When the user click on the "Sign in" button which have an event attached, I retrieve the form information and make an ajax call to the '/login' route but it does not work ..

Here a list of the necessary files :

Thank you for your help.

Upvotes: 0

Views: 141

Answers (2)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123483

The issue is that the form is still submitting via redirect as that's its default bahavior and it hasn't been instructed to do otherwise. And, because of the redirect, the browser is is aborting the Ajax request.

To prevent the redirect, you'll want to bind to the .submit() event of the <form> and use event.preventDefault():

$(document).ready(function () {
    $('#login-form').submit(function (e) {
        e.preventDefault();
    });
});

It may also be worthwhile to use this event for the Ajax rather than the .click() of the <button> as many browsers allow submitting through other actions besides just clicking a type="submit" button (e.g., pressing Enter when focus is on a <input type="text">):

$(document).ready(function () {
    $('#login-form').submit(function (e) {
        e.preventDefault();

        var _login = $('#login').val(),
            _password = CryptoJS.SHA512($('#password').val()),
            _remember = $('input:checkbox:checked').val() ? 1 : 0;

        // etc.
    });
});

Upvotes: 1

numbers1311407
numbers1311407

Reputation: 34072

For one, you need to prevent the default action from the button click:

$('#btn-login').click(function () {
  // ...
});

// should accept the passed event and `prevenDefault`, like...

$('#btn-login').click(function (e) {
  e.preventDefault();
  // ...
});

Upvotes: 0

Related Questions