Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

220
Vistas
Flash NodeJS error to user?

I'm using Ajax and Node JS to let a user register on a one page application. When the user hits register I have it set up to check to see if the username is taken. All of this works so far. Now however, I am needing to alert the user that their username is taken. How would I print the error or flash the error to the user this way? The problem is I am avoiding page refreshes.

app.post("/quiz", function(req, res, next){
    User.findOne({username: req.body.username}, function(err, user){
       if(err) { console.log(err)} 
      if(user) { 

       console.log(user)
        // I NEED TO SEND THE ERROR HERE SAYING THE USERNAME IS TAKEN     
        // I NEED TO SEND THE ERROR HERE SAYING THE USERNAME IS TAKEN     
        // I NEED TO SEND THE ERROR HERE SAYING THE USERNAME IS TAKEN     
      }

    });

       //continue with your registration logic
       var newUser = new User({username: req.body.username, datapoint: req.body.datapoint});
         User.register(newUser, req.body.password, function(err, user){


        // if(res.error){

             if(err){
               req.flash("error", err.message);
               res.redirect('back')
               return res.render("quiz");

           } else {

           passport.authenticate("local")(req, res, function(){
           //   req.flash("success", "Welcome to JobQuiz " + user.username);
             res.redirect("jobquiz");
             console.log(req.body.datapoint)
           });
           }
       });



});

Ajax set-up

   $(function() {
                $("#checkpaymentForm").on("submit", function(e) {
                    e.preventDefault();
                    $.ajax({
                    url: $(this).attr("action"),
                   type: 'POST',
                   data: $(this).serialize(),
                   dataType:'json',
                })
                });
   });
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

First send your response in the if statement in the server code:

app.post("/quiz", function(req, res, next){
    User.findOne({username: req.body.username}, function(err, user){
       if(err) { console.log(err)} 
       if(user) { 
            res.json({"message": "false" });
       }

 });

Then in your front end add the success function to handle the response:

   $(function() {
            $("#checkpaymentForm").on("submit", function(e) {
                e.preventDefault();
                $.ajax({
                  url: $(this).attr("action"),
                  type: 'POST',
                  data: $(this).serialize(),
                  dataType: 'json',
                  success: function (data) {
                    if (data.message === "false") {
                        //TODO: alert users here
                    }
                 })
            });
   });
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda