Search code examples
javascriptnode.jsajaxexpressexpress-handlebars

Why does this AJAX call not redirect to the `/login` URL?


I am making a Node Express app with Handlebars.

I get a success message printed in the console but the URL is not changed to /login, and hence the page never gets rendered, although, when I manually type the URL localhost:3000/login into the browser, I can see my login page rendered.

Therefore, I wanted to know why the AJAX is not working.

index.handlebars:

<a class="btn" id="login" target="login">Login</a>

login.handlebars:

<input placeholder="Email" name="email" id="email" type="text">
<input placeholder="Password" name="password" id="password" type="password">

index.js:

const baseUrl = 'http://localhost:3000';

$("a[id='login']").click(function(){
  $.ajax({
    url: `${baseUrl}/login`,
    method: 'GET',
    success(){
      console.log('success');
    },
    error(e){
      console.log(e);
    }
  });
});

routes file:

router.get('/login', function(req, res)=>{
  try{
    res.render('login');
  }
  catch(e){
    res.status(401).json({
      message: 'Failed'
    });
  }
});

Solution

  • An Ajax call just sends a request to your server and gets the response back to your Javascript. It does not, by itself, change ANYTHING in the browser window. If you want to go to the /login page after your ajax call, then you can tell the browser to go to /login by setting window.location = "/login" in your browser Javascript.

    But, what it looks like you really want to do is to just change the window location instead of even using the ajax call since the Ajax call by itself isn't doing anything except render a login form.

    const baseUrl = 'http://localhost:3000';
    
    $("a[id='login']").click(function(){
          // now render the login page
          window.location = "/login";
       });
    });
    

    But, since all this is doing is sending the browser to a new web page, you don't even need Javascript for this, you would just use an <a href="/login">Login<a> in your page too.