Suchitra Iyer Suchitra Iyer - 1 year ago 74
Node.js Question

redirecting a page and displaying a message through javascript

I have an HTML page which provides input fields for email ID and password, I use these values to connect with my backend SQL server through node js express application .

I have an method to connect with SQL.'/user', function (req, res, body) {
uid = req.body.user1;
pwd = req.body.user2;

config = 'Server={ip of server};Database=Dbname;Uid=domain\\user' + uid + ';Pwd=' + pwd;

var dbConn = new sql.Connection(config);
dbConn.connect().then(function () { //using promises instead of callbacks(onceconnect() is done), then go to then()

var request = new sql.Request(dbConn);
res.status(500).json({ status: 'done' })

}).catch(function (err) {

res.status(500).json({ status: 'invalid' })

What I want to achieve is -

  1. If the credentials are valid, displaying an alert 'DONE' at client side.

  2. If the credentials are invalid, displaying an alert 'INVALID' at client side.

Currently, if everything is valid, there is DONE at /user.
If the ID and Password do not match, there is INVALID at /user.

My client side code is

<!DOCTYPE html>


<form id ="target" action="/user" method="post">
UserID : <input id="uid" type="text" name="user1" /> <!text fields for date input>
Password : <input id="pwd" type="password" name="user2" />

<input id="Submit1" type="submit" value="LOGIN"/> <!--<!submit button>-->
<input id="Button" type="button" value="show graphs" onclick="btntest_onclick()" />

$.post("/user", function (data) {
alert( "Data Loaded: " + data );

<script type="text/javascript">
function btntest_onclick() {

setTimeout(function () {

window.location.href = "/../";

I am unable to use $.post() on client to retrieve data back from user- gives 500 error.
How do I proceed? Please help me.

Answer Source

I could solve this by using the jquery ajax callback that returns back data to the client.

$("#target").submit(function (event) {

    var formData = {
        'uid': $('input[name=uid]').val(),
        'pwd': $('input[name=pwd]').val()

        type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url: '/user', // the url where we want to POST
        data: formData, // our data object
        dataType: 'json', // what type of data do we expect back from the server
        encode: true
     .error(function (data) {

         // log data to the console so we can see
    .done(function (data) {

        // log data to the console so we can see

        // here we will handle errors and validation messages

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download