I'm a newbie to AJAX, and node.js and am learning it more as the hours passes but I am stuck on this issue. It's a simple client-side ajax post to the server-side. I'm posting a JSON object that I want to save to my MongoDB w/ Mongoose. I tried various things such as JSON.stringify() but I don't fully comprehend what I am doing so I can't diagnose. How can I post the JSON object and save it into MongoDB? Thank you.
main.js
function addTask(event){
event.preventDefault();
var newTask = {'local':{
'id': $('#datepicker').val(),
'project': $('#selectProject').val(),
'task': $('#selectPTask').val(),
'hours': $('#hours').val()
}};
$.ajax({
type: 'POST',
data: newTask,
url: '/tasks',
dataType: 'JSON'
}).done(function (response){
//if ajax successful
if (response.msg === '') {
//update table
populateTable();
}
else {
//if something went wrong, alert
alert('Error: ' + response.msg);
}
});
};
routes.js
app.post('/tasks',function(req,res){
console.log(req.body.id)
console.log("adding new task" + req.body.date + req.body.hours);
var newTask = new Task();
newTask.local.id = req.body.id;
newTask.local.project=req.body.project;
newTask.local.task=req.body.task;
newTask.local.hours=req.body.hours;
newTask.save(function(err){
if (err) return handleError(err);
});
});