I have a post tags functionality for my website: Tag functionallity. have a look at this code, I grab that tags with javascript and save them into tags array:
var formNewPost = $("#formNewPost");
formNewPost.on("submit", function (event) {
var tagElements = $("span.tag span");
var tags = [];
for (var i = 0; i < tagElements.length; i++) {
var text = document.querySelectorAll("span.tag span")[i].innerText;
text = text.trim();
tags.push(text);
}
});
now I have my suitable array, now I wanna save that into my mongoDB database. my node js code:
var title = req.body.title;
var tags = // I want that array from client side to be here
var type = req.body.type;
var body = req.body.body;
var author = req.body.author;
var newPost = {title, author, tags, type, body, author};
Post.create(newPost, function (err, newPost) {
if (err) {
req.flash('error', 'An error occurred, please try again.');
res.redirect('/posts/new');
} else {
req.flash('success', 'Post created successfully.');
res.redirect('/posts');
}
});
But how can I do that? I tried this code but it is not working at all:
tags.push(text);
$.ajax({
type: "POST",
url: '/posts',
data: { tags : tags },
success: function(data)
{
alert("success!");
}
});
then grab that data with express:
var tags = req.body.tags; // AN ARRAY FROM JAVASCRIPT
But it is not working at all, what is the problem?