I am a beginner to nodejs and I am trying to send response from nodejs to ajax on client side. Everything is working fine, but the problem is as the response is received on clent side, a new page openes and the response is shown on that page. It means that the core functionality of ajax is not fulfilled. I want the ajax response to be displayed on the same page. Please help!! Below is my server code:
app.post('/auth',function(req, res){
console.log(req.body);
var username=req.body.username;
var password=req.body.password;
var obj={};
if(username&&password){
connection.query('select * from signup where username=? and password=?',[username,password],function(err, result){
if(err) throw err;
if(result!=0)
{
req.session.loggedin=true;
req.session.username=username;
return res.redirect('/home');
}
obj={'message':'Incorrect Username and/or Password'};
obj=JSON.stringify(obj);
res.send(obj);
});
}
});
This is my client side code. I want the response to be displayed inside the label with id "wrongdetail" but it is being printed on another page. Below is my jquery ajax call:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#submitbut').click(function(){
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost:3000/auth',
success: function(response) {
$('#wrongdetail').html("<b>"+response.message+"</b>");
}
});
});
});
</script>
<!DOCTYPE html>
<html>
<head>
<title>Login page</title>
</head>
<body>
<div class="login-form">
<h3>Sign In</h3>
<form action="auth" method="post" class="form-content">
<label for="username"><b>Username</b></label>
<input type="text" name="username" placeholder="Enter Username ..." id="usernm" required>
<label for="password"><b>Enter Password</b></label>
<input type="password" name="password" placeholder="Enter Password ..." id="passwd" required>
<label for="wrong" id="wrongdetail"></label>
<button id="submitbut">Login</button>
</form>
</div>
</body>
</html>