I am trying to send form data to server side using ajax (sending a username), and in the server side perform SQL query and pass back the result to my template (EJS).
In my server side (ajaxTest.js)
router.post('/', function(req, res){
console.log(req.body);
var query = connection.query("select * from account where username='" + req.body.username+ "'",function (err,result) {
console.log(query.sql);
if (err) {
console.error(err);
return;
}
console.error(result);
res.send("Result "+JSON.stringify(result));
});
});
In my template (ajaxTest.ejs)
$(document).ready(function () {
$("#submit").on("submit",function (e) {
e.preventDefault();
data = {};
data.username = 'user101';
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'http://localhost:3000/ajaxtest',
success: function(data) {
console.log('success');
console.log(JSON.stringify(data));
}
});
})
});
In the above code, result is successfully logged onto my console, but the 'success' and data does not get returned. Is there a reason why result is not being sent back to the template (ajaxTest.ejs)?
I'd greatly appreciate any feedback on the situation!
res.json(JSON.stringify(result))?