0

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);
    });
});
SolidSnake
  • 135
  • 1
  • 11
  • do this var newTask = { 'id': $('#datepicker').val(), 'project': $('#selectProject').val(), 'task': $('#selectPTask').val(), 'hours': $('#hours').val() }; it will be fine this way – Jalasem Nov 14 '17 at 08:13
  • Thanks, I tried that but couldn't seem to work on the server-side. I'm having trouble accessing the data on the server-side and saving it into my db. – SolidSnake Nov 14 '17 at 08:17
  • I figured it out. Didn't have to use stringify. It was an error with my val(), some of them were undefined and I guess threw the whole thing off. – SolidSnake Nov 14 '17 at 08:30
  • first console.log(JSON.stringify(req.body, null, 2)) to see what you are getting from the ajax request at the server side – Jalasem Nov 14 '17 at 08:31
  • 1
    great! You found a solution – Jalasem Nov 14 '17 at 08:32

0 Answers0