Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda