Monday, 5 June 2017

unable to fetch data from ejs to controller and client side JS

I am a newbie in node and express. I am working on an app that has a login module. I am able to register a user but am facing some issues while trying to log in a user.

Please find my code below and suggest:

Logincontroller.js

app.post('/testAction',urlencodedParser,function(req,res){

    var usrnm = req.body.username;
    console.log(" usrnm ::: " + usrnm);
    var passwd = req.body.password;
    console.log(" passwd ::: " + passwd);
    Users.findOne({username:"tstusr1"},function(err,data){ // Users is my schema name
        if(err) throw err;
        console.log(" back from ajax with data in login controller :::; " + data);
        res.json(data);
    });
    console.log("inside index2 post");
});

my Login-user.js is

$(document).ready(function(){

      var items = $('form');
      var user ={username: $('[name=username]', items).val()};     
      console.log('user  ' + JSON.stringify(user));

  $('form').on('submit', function(){
      console.log("inside submit login");
      $.ajax({
          type: 'POST',
          url: '/testAction',
          data: user,
          success: function(data, textStatus, jqXHR){
            var resp = JSON.parse(JSON.stringify(jqXHR));
            if(resp["status"]==200){
                console.log("status == 200");
                window.location.href = '/';
            }  
              return data;
          },
          error:function (jqXHR, textStatus, errorThrown) {

              console.log('error  ' + JSON.stringify(user));
              console.log("resp1 :::::: " + JSON.stringify(jqXHR));
              var resp = JSON.parse(JSON.stringify(jqXHR));
              console.log("resp :::::: " + resp);
          }
        });
         return false;
  });  
});

And my ejs file is

<form action="/testAction">
    <label for="username"> Username </label>
    <input type="text" for="username" name="username" />
    <label for="password"> Password </label>
    <input type="password" for="password" name="password" />
    <button type="submit">Log In</button> 
</form>

My issue is I am not able to fetch the values of username and password to the client side js as well as backend server side js.

Please assist



via Saurabh Jhunjhunwala

No comments:

Post a Comment