Andrew Little Andrew Little - 7 days ago 7
jQuery Question

Why is my ajax call only handling part of the data i am sending to my server?

I am trying to use Ajax to upvote a post. Iin addition to sending upvote data, I want to send the ID of the post so that I can eventually use findOneAndModify from mongoose to target that specific post and upvote by 1. For some reason, I can use ajax to upvote a specific post, but sending the object ID back to the server isnt working.

here is my JADE client code

each post in posts
.media.white.paddingBoxForPost
.media-left.media-middle
a.removeTextDeco(href=post.link, target='_blank')
img.media-object(src=post.img, alt='facebook logo')

.media-body
a.removeTextDeco(href=post.link, target='_blank')
div#mainTitlePost.media-heading.postTitleFont= post.title
div#mainShortDesc.descriptionFont= post.description
form(method="post")
label(for='upvote')
.form-group
select#mainPostId.postIdentity.hidePostId.form-control(name='upvote')
option= post._id
button.upvoteClick.btn.btn-lg.btnColor(type='submit')
span.glyphicon.glyphicon-fire 3
button.btn.btn-lg.btnColor(type='submit')
span.glyphicon.glyphicon-comment


And here is my Ajax call

$(function () {

$(".upvoteClick").click(function () {

var postID = {postID: $('.postIdentity').val()};
var upvoteIncrement = {upvote: 1};

// alert(postID);
// console.log(postID);


$.ajax({
type:"POST",
data: upvoteIncrement, postID,
dataType: 'json',
url:"http://localhost:9000/api/upvote"
}).success(function (data) {
// console.log(data);
// console.log('Process success');

})
})
});


And finally here is my server code

router.post('/upvote', function (req, res, next) {

var data = req.body.upvote;
var query= {title: "Will this work"};
var update = {$inc: {upvote: data}};
var options = {new: true};
var Upvote = mongoose.model('Upvote', schema);
var mongoPostId = req.body.postID;


console.log(mongoPostId);
console.log(data);

Upvote.findOneAndUpdate(query, update, options, function (err, posts) {
if (err){
console.log('got an error in your DB');
res.sendStatus(200);
}});
// .then(() => res.sendStatus(200))
// .catch(next);

console.log('process SHOULD be done');
// console.log(data);



});


in console.log(mongoPostId) I keep getting undefined. However the problem is somewhere with my ajax call because I can't seem to send the postID variable along with the upvoteIncrement variable.

Thank you in advance.

Answer

Your ajax() config is missing object notation for the data value, so postID is getting set in the ajax() config object instead of the data object. Try this instead:

data: { upvoteIncrement, postID },

Also, your upvote value will be at upvoteIncrement and not just upvote like you currently have in your server-side code.

Comments