I have a form for submitting post data to a database with Ajax that looks like this:
function markAsRead(id) {
console.log('Triggered');
$.ajax({
type: 'POST',
url: '/admin/assessment.html',
data: id,
success: function(data) {
if (data.error) {
console.log('We had an error.');
} else if (data.success) {
console.log('Marker updated.');
}
}
})
}
(function() {
var element = document.getElementsByName('markAsRead');
for(var i = 0; i < element.length; i += 1) {
element[i].addEventListener('click', function(e) { e.preventDefault;
markAsRead(this.getAttribute('data-value'));
});
}
})();
I have multiple Anchors on my page that look like this for example:
<a href="#" name="markAsRead" data-value="5135135">Mark As Read</a>
I'm just wondering on the Node.js side of things, how might I parse that data, I Tried:
var id = req.body.markAsRead;
console.log('Data is ' + id);
But it just says undefined. Any information would be great on how to parse this request data. Thanks! (The Anchor is not inside any form)
First, you should be POSTing data from the client with named parameters, or something more structured than a string.
$.ajax({
type: 'POST',
url: '/admin/assessment.html',
data: { id: id },
success: function(data) {
if (data.error) {
console.log('We had an error.');
} else if (data.success) {
console.log('Marker updated.');
}
}
})
Second, when you parse the req.body on the node side, you're parsing the string that is sent as the request body, which includes your parameters { id: 'somevalue' }. You could parse this yourself, but I'm guessing you're using something like express or another abstraction on top of node's http.Server implementation that supports a middleware stack. I recommend using the connect bodyParser() middleware, which will convert the req.body string into an object with properties that were posted. This will make req.body.id available to you in your request handler in node.