简体   繁体   中英

jquery ajax succefuly sends data but done fail always doing nothing

I'm doing a signin page for my nodeJs app.

When i'm submitting my form, all the data are send to my node app (so it's great),

but the done, fail, always functions of jquery ajax just don't work at all at first, and after some time (like a lot), it calls the fail and always function. Dunno what's wrong in my code, no error at all.

Here is my html client code :

<!doctype html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Gatsbill</title>
    <link rel="stylesheet" href="public/css/reset.css">
    <link rel="stylesheet" href="public/css/connection.css">
</head>
<body>
    <div id="content">

        <a href="http://localhost:3001"><img src="public/images/icone.jpg" alt="gatsbill"></a>

        <div id="wrap">

            <div id="subscribe">
                <a href="http://localhost:3001/login" class="click">Se connecter</a>
                <p id="p">Pour vous inscrire,<br> Veuillez remplir les champs ci-dessous</p>
                <div id="message" class="message" style="display: none;"></div>
                <form method="post" id="form">
                    <input type="text" name="username" placeholder="Username" required autofocus id="username">
                    <input type="email" name="mail" placeholder="Email" required id="email">
                    <input type="password" name="password" placeholder="Password" required id="pass1">
                    <input type="password" name="password2" placeholder="Password" required id="pass2">
                    <input type="submit" name="submit" value="Create account" id="submit">
                </form>
            </div>

        </div>
    </div>

    <!-- Script -->
    <script src="public/js/jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="public/js/signin.js"></script>


</body>
</html>

My javascript client code :

$(document).ready(function() {
    $("#form").submit(function(event){

        event.preventDefault();

        $("#p").hide();
        var pass1 = $('#pass1');
        var pass2 = $('#pass2')


        if (pass1.val().length > 6) {
            if (pass1.val() == pass2.val()) {

                var data = {
                    username: $("#username").val(),
                    email: $("#email").val(),
                    pass: $("#pass1").val()
                };

                var $inputs = $("#form").find("input, select, button, textarea");
                $inputs.prop("disabled", true);

                $.ajax({
                    url: "http://localhost:3001/signin",
                    type: 'post',
                    data: data,
                    dataType: 'json'
                })
                .done(function(data) {
                        alert("done");
                        console.log(data);
                })
                .fail(function( html ) {
                        alert('fail');
                })
                .always(function( html ) {
                        $inputs.prop("disabled", false);
                });

            } else {
                $('#message').text('Les mots de passes doivent être identiques').show();
                pass1.val('');
                pass2.val('');
            }
        } else {
            $('#message').text('Le mot de pass doit faire au moins 7 caractères').show();
            pass1.val('');
            pass2.val('');
        }

    });
});

and this is my node app, just checking post values at the moment

var express = require('express');
var swig = require('swig');
var ent = require('ent');
var bodyParser = require('body-parser');
var mongojs = require('mongojs');
var passport = require('passport');

var app = express();
var server = app.listen(3001);
var io = require('socket.io').listen(server);

// Environnement
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/public", express.static(__dirname + "/public"));
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.set('view cache', false);
swig.setDefaults({ cache: false });

//MongoDB
var db =  mongojs("mongodb://127.0.0.1:27017/maBase", ["users"]);



// Page Principale
app.get('/home', function(req,res){
    res.render('login.html',{});
});

// Page connection
app.get('/', function(req,res){
    res.render('index.html',{});
});

app.route('/signin')
    .get(function(req, res, next) {
        res.render('signin.html',{});
    })
    .post(function(req, res, next) {
        if (req.body.email) {
            console.log(req.body.username + req.body.email + req.body.pass);
        }
        else {
            console.log('not ok')
        }
    });

app.route('/login')
    .get(function(req, res, next) {
        res.render('login.html',{});
    })
    .post(function(req, res, next) {

    });

Your client side JS code looks fine. The problem is with your server side code. In the /signin POST request function you are not giving any response(You are just logging it in the console). That is why your client side JS code does not get any kind of response to process whether it is "success" or "failure". That is why after trying for a lot of times, it finally goes into "always". The always function is executed either in an event of server timeout or situations where there is no response. Try returning a response from your signin function. You could do this by using the ".json" method provided by the "res" parameter that you are passing to your request function.

Like this:

app.route('/signin')
.get(function(req, res, next) {
    res.render('signin.html',{});
})
.post(function(req, res, next) {
    if (req.body.email) {
        console.log(req.body.username + req.body.email + req.body.pass);

        res.json("Success");
    }
    else {
        console.log('not ok')

        res.json("Error"); 
    }
});

Or anything else that you want to return from the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM