1

I am new to express with EJS.

I tried making a ajax post request for submitting to the values to the DB using.

 $.ajax({
    type: 'POST',
    url: '/register',
    data: user,
    success: function(data){
        console.log(data);
        return data;
    }
  });

  return false;

This call is successful and after which the control goes to the calling function

var sess;

  app.post('/register',urlencodedParser,function(req,res){
    sess=req.session;
    var newUsr=Users(req.body).save(function(err,data){
      if(err) throw err;
      console.log(" back from ajax with data :::; " + data);

      console.log("step1 cleared");
      sess.registered=true;

    });
    console.log("step2 cleared");
    location.window.href = '/index2';
  });

I want the user to see the index page once the registration is successful, but I am getting the below error.

ReferenceError: location is not defined

I think location object is not there in node, thus this error, but again I dont know how to fix this issue, please suggest

VVV
  • 7,563
  • 3
  • 34
  • 55
Saurabh Jhunjhunwala
  • 2,832
  • 3
  • 29
  • 57
  • `window` is the global object in the browser's javascript run-time. and in node the global object is called `global`, which doesn't have location – Omri Luzon May 27 '17 at 19:58
  • see this : https://stackoverflow.com/questions/11355366/nodejs-redirect-url – niceman May 27 '17 at 20:01
  • 1
    Logic is all wrong. Can't create a redirect on server for browser to go to in an ajax request. Consider returning response object that tells client side code that it either needs to redirect or consume the response data – charlietfl May 27 '17 at 20:20

1 Answers1

1

In Node.js you can use res.redirect('/'), but it works only with GET requests. The right way in this situation is to return response from server with redirect status code: 302 and in your ajax script check if status code equals to 302 change location.

Your code should look like this:

$.ajax({
   type: 'POST',
   url: '/register',
   data: user,
   success: function(data, textStatus, response) {
     if(response.status === 302) {
        window.location.href = '/index2';
     }
     return data;
   }
 });

Server side code:

var sess;

app.post('/register', urlencodedParser, function(req, res) {
  sess = req.session;
  var newUsr = Users(req.body).save(function(err, data) {
    if (err) throw err;
    console.log(" back from ajax with data :::; " + data);

    console.log("step1 cleared");
    sess.registered = true;

    res.status(302).send('User saved successfully');
  });
});
kaxi1993
  • 4,535
  • 4
  • 29
  • 47