while submitting a form without using ajax I could see "message sent successfully" in my http://localhost/ss (working fine as it should)
But while submitting a form using ajax $.post() response is not receiving to $.post() method. I couldn't find any reason..
Please note: same code works fine with php
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#buttons").click(function() {
$.post("http://localhost:3000/ss", {
sendemail: $("#email").val(),
sendname: $("#UserName").val(),
sendpass: $("#Password").val()
}, function(res) {
alert(res);
});
});
});
</script>
<body>
<div class="forms">
<form>
<div class="formdiv">
<label>User Email</label>
<input type="email" id="email" name="email" />
</div>
<div class="formdiv">
<label>User Name</label>
<input type="text" name="UserName" id="UserName" />
</div>
<div class="formdiv">
<label>User Password</label>
<input type="password" name="Password" id="Password" />
</div>
</form>
<div style="background:green;padding:15px;" id="buttons">send</div>
</div>
</body>
</html>
parse.js
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.listen(3000, function(req, res)
{
console.log("express is listening to port 3000");
});
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json());
app.get("/", function(req, res)
{
res.send("hai");
});
app.post("/ss", function(req, res)
{
var ss = req.body.sendemail;
if (ss != undefined)
{
console.log(ss);
res.send("message sent successfully");
}
else
{
res.send("error occurred");
}
});
console prints user's email address "The only problem is response to html"
Code looks okey by itself, although there's one issue, with (i suspect) the way you use it. You're not allowing for cross-origin sharing. In other words, if you'd try to run this code on another domain, you'd receive a CORS error, as server refuses to respond to the client.
Therefore, I suspect you're loading the .html file either:
both of those would (and are) returning mentioned above error. That's why you're not receiving the response, so you're not seeing the alert message.
In order to bypass the issue, you can either:
Example here:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var path = require("path");
...
app.get("/", function(req, res)
{
res.sendFile(path.join(__dirname + '/index.html'));
});
app.post("/signup", function(req, res)
{
var email = req.body.email;
if (!email)
{
return res.json({
message: "error occurred"
});
}
res.json({
success: true;
});
});