I am trying to make a comment form which adds a comment in array of blog schema
but when I am using ajax it is giving undefined below the places where I have console log and when I am using simple post request it is working fine.
I am using mongoose, nodejs , express, jquery ajax
my script is as follows
var frm = $('#commentForm');
frm.submit(function (e) {
e.preventDefault();
console.log('clicked');
$.ajax({
type: 'POST',
url: "/blog/addComment",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function(data) {
addNewComment(data);
})
.fail(function() {
console.log("Ajax failed to fetch data");
});
});
function addNewComment(data){
console.log(data);
}
my routes is as follows
//add comments
router.post('/addComment',function(req,res,next){
console.log(req.body.comment+" "+ req.body.userId+" "+req.body.postId);
var newComment = {
'text': req.body.comment,
'author': req.body.userId
}
Post.addComment(req.body.postId, newComment, function(err,comment){
if(err) throw err;
console.log(comment);
res.send(comment);
});
});
and my mongoose schema is
//add comments
module.exports.addComment = function( postId, newComment, callback){
var query = { '_id': postId};
console.log('postid: '+postId+" newcomment: "+newComment.text+ " "+newComment.author);
Post.findOneAndUpdate( query, { $push:{'comments': newComment} }, {new:true} , callback);
}
That's because data is not defined in ajax call ,
use following provide the frm is the actallu form or use
use data : form name.serialize()
var frm = $('#commentForm');
frm.submit(function (e) {
e.preventDefault();
console.log('clicked');
$.ajax({
data : $(this).serialize(),
type: 'POST',
url: "/blog/addComment",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function(data) {
addNewComment(data);
})
.fail(function() {
console.log("Ajax failed to fetch data");
});
});
Related
I have a text area with id "text" and I am toggling the text area to appear on the screen with a click event on some div and I have 30 such divs.
Initially , I'm assigning the textarea.value with result of ajax call to my fetch api which fetches the data from the mongo on the server side based on an unique id.
Sometimes , when I'm making the ajax call to my update api in my backend , the textarea.value I'm sending as data to this ajax call is not the same as the updated text of the text area.
//client side
// called when any of the divs is clicked
$(".radius").on("click", function(event) {
//extracting the id from the class and using this id as the id of my data for my mongo
var st=event.target.classList[1].substring(0,7);
var num=parseInt(event.target.classList[1].substring(7));
var toadd="close-button"+num;
//console.log(num+"modal")
closeButton.classList.add(toadd);
$.ajax({type: "POST",
url: "/fetch",
async: true,
data: JSON.stringify({
id: num,
}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success:function(result) {
input.value=result.text;
},
error:function(result) {
console.log("error")
}
});
modal.classList.toggle("show-modal");
});
// called when textarea is closed
function toggleModal1(event) {
var s1=closeButton.classList[closeButton.classList.length-1];
var st=s1.substring(12);
closeButton.classList.remove(s1);
var num=parseInt(st);
// event.preventDefault();
console.log(input.value)
$.ajax({type: "POST",
url: "/update",
data: JSON.stringify({
id:num,
text:input.value,
//input is my textarea
}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success:function(result) {
},
error:function(result) {
console.log("error")
}
});
modal.classList.toggle("show-modal");
}
//server side
app.post("/fetch",function(req,res)
{
//console.log(req.body);
// var id1=req.body.id;
const findInDB= Fruit.findOne({id:req.body.id},function (err, docs) {
console.log(docs);
res.send({text:docs.text});
});
});
app.post("/update",function(req,res)
{
Fruit.updateOne({id:req.body.id},
{text:req.body.text}, function (err, docs) {
if (err){
console.log(err)
}
else{
console.log("Updated Docs : ", docs);
}
});
I'm trying to insert data into MongoDB using Mongoose, i created a form and sending data using two ajax post to the node, but Mongoose insert two document for each ajax call, I want to send my data to data as a single document.
This my server:
app.post("/cp" , upload , function(req , res){
console.log('file uploaded succcessfully');
var title = JSON.stringify(req.body.titles);
var file = req.file;
const courses = new Courses({
// courseTitle:c_title,
// courseSubtitle:c_subtitle,
// courseAuthor : c_creator,
// coursePrice : c_price,
courseVideo :file ,
courseTitles :title ,
// courseSpecs : c_specs,
courseValidation : 0
});
courses.save();
});
Mongoose insert a document with title and without file and a document with file and without title,
Ajax:
if(e.submitter.id == "submitpostCp"){
var data = {};
data.titles = titlesLis;
data.specs = specsLis;
data.submit = "submitAll";
var fileup = new FormData($('#form')[0]);
$.when(
$.ajax({
type: 'post',
url: '/cp',
data: JSON.stringify(data),
contentType: 'application/json',
xhrFields: {
withCredentials: false
},
headers: {
},
success: function (data) {
console.log('Success');
console.log(data);
},
error: function () {
console.log('We are sorry but our servers are having an issue right now');
}
})
).then(function() {
$.ajax({
url:'/cp',
type: 'POST',
contentType: false,
processData: false,
cache: false,
data: fileup,
success: function(res){
// alert(res);
},
error: function(){
alert('Error: In sending the request!');
}
})
});
}
In this case you should use findOneAndUpdate method with options {upsert: true}: https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
Right now i have the following code below, this code posts some data to my page and waits for a response of status = SUCCESS or Failure. I am trying to understand if this is async or sync. How can I make this JavaScript query wait for the response and then run what is inside success? It doesn't seem to wait for the response of what it is posting to.
Thanks!
my.submit = function() {
var form = $('#lines');
console.log(form)
var data = form.serialize();
console.log(data)
$.post('', form.serialize(), function(json) {
console.log(json)
if(json.status === 'SUCCESS') {
console.log('success');
window.open(json.imgid, '_self');
} else {
console.log('failure');
}
}, 'json');
$('#progress_bar').show();
}
I then tried to work on making it work the way i wanted by editing the code below but now its just returning the HTML contents of the entire page rather than the JSON response. Any idea why its not getting the JSON response?
my.submit = function() {
var form = $('#lines');
console.log(form)
var data = form.serialize();
console.log(data)
$.ajax({
url: '',
type: 'POST',
data: data,
success: function(json) {
console.log(json)
if (json.status === 'SUCCESS') {
console.log('Success!');
} else {
console.log('An error occurred.');
console.log(data);
}
}
}, 'json');
$('#progress_bar').show();
}
Add dataType: 'json', below data: data,
my.submit = function() {
var form = $('#lines');
//console.log(form)
var data = form.serialize();
//console.log(data)
$.ajax({
async: false,
url: '',
type: 'POST',
data: data,
dataType: 'json',
success: function(json) {
console.log(json)
if (json.status === 'SUCCESS') {
console.log('Success!');
window.open(json.imgid, '_self');
} else {
console.log('An error occurred.');
console.log(data);
}
}
}, 'json');
$('#progress_bar').show();
}
Okay, this seems to be the most straight forward thing, but I really have no idea why it's doing this nor find anyone else with this problem.
Here's my issue, I'm sending a POST request like so;
$.ajax({
type: "POST",
url: '/user/sell',
data: data,
success: function(data) {
console.log('Call was successful');
}
});
In the data object is an array called items. When I log the data object it's fine, like it should be, however when I log the data object in my express function the items array changes to items[] for no reason..
NodeJS
'items[]': '15716345'
JS (Browser)
items: [15716345]
Any idea what's happening here?
Below is the entire version of the code.
Entire block (frontend)
// Validate address
if($('.block.payment .wrapper input:eq(0)').val() !== $('.block.payment .wrapper input:eq(1)').val()){
return error('Fields do not match');
}
// Get known data
var type = $('.body.inventory .methods .method.selected').data('type'),
items = [];
var data = {
type,
address: $('.block.payment .wrapper input:eq(0)').val()
}
if(type === 'steam'){
var app = $('.body.inventory .sub-methods .method.selected').data('app');
data['app'] = app;
$('.body.inventory .item[data-app="'+app+'"].selected').each(function(){
items.push($(this).data('id'));
});
}else{
$('.body.inventory .item[data-type="'+type+'"].selected').each(function(){
items.push($(this).data('id'));
});
}
data['items'] = items;
// Execute route or smt
$.ajax({
type: "POST",
url: '/user/sell',
data: data,
success: function(data) {
console.log('Call was successful');
}
});
Backend
router.post('/sell', function(req, res, next) {
try {
console.log(req.body);
res.send({
success: 1
});
} catch(e) {
if(e) console.log(e);
res.send({
success: 0,
error: e
});
}
});
Set JSON body parser middleware for requests to your expressJS application.
const bodyParser = require('body-parser');
app.use(bodyParser.json())
And in the AJAX request, make the contentType to be application/json and not the default of application/x-www-form-urlencoded; charset=UTF-8'.
$.ajax({
contentType: 'application/json',
type: "POST",
url: '/user/sell',
data: data,
success: function(data) {
console.log('Call was successful');
}
});
Assume that is your Array List, which you want to POST.
object[] Obj = new object[1];
Obj [0] = "value1"
Obj [1] = "Value2"
Obj [3] = {"CollectionValue1, CollectionValue2"}
$.ajax({
url: '../Controller/MethodName',
type: 'post',
datatype: 'json',
async: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ ControllerParameterName: Obj }), <!-- Obj is your Array -->
success: function (data) {
alert(data.Response);
}
});
I have three functions that called as shown below (Functions not included):
Code:
$("#btnSubmit").click(function() {
var data = JSON.stringify(getAllSourcepData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveSourceData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
});
$("#btnSubmit").click(function() {
var data = JSON.stringify(getAllSpouseData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveSpousData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
});
$("#btnSubmit").click(function() {
var data = JSON.stringify(getAllDividentData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveDividentData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
});
When data is submitted successfully, three alert boxes popup, each with same message: "Data Added Successfully".
This forces user to have to close three popup boxes.
Is there a way to disable the success alert boxes leaving just one? Or even all three be disabled allowing me to come up with a custom Success message?
You could also simplified your code by using Promise.all:
$("#btnSubmit").click(function() {
var allSourcepData = JSON.stringify(getAllSourcepData());
var allSpouseData = JSON.stringify(getAllSpouseData());
var allDividentData = JSON.stringify(getAllDividentData());
Promise.all([
getData('closures.aspx/SaveSourceData', allSourcepData),
getData('closures.aspx/SaveSpousData', allSpouseData),
getData('closures.aspx/SaveDividentData', allDividentData)
])
.then( alert )
.catch( alert )
});
function getData(url, data)
{
return new Promise((resolve, reject){
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: () => { resolve("Data Added Successfully") },
error: () => { reject("Error while inserting data"); }
});
})
}
You need to wait until all ajax requests are complete, like in this answer
So in your case you need to create functions for all $.ajax calls like this:
function ajax1() {
var data = JSON.stringify(getAllSourcepData());
$.ajax({
url: 'closures.aspx/SaveSourceData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'empdata': data
}),
success: function() {
alert("Data Added Successfully");
},
error: function() {
alert("Error while inserting data");
}
});
}
// add ajax2() and ajax3() ...
And then use only one click handler like this:
$("#btnSubmit").click(function() {
$.when(ajax1(), ajax2(), ajax3()).then(function(a1, a2, a3){
// success, display message
}, function(){
// exception
});
});
You can reorder a little your code to use the deferred method to jQuery 1.5+ otherwise you can implement as this answer:
jQuery callback for multiple ajax calls
Why you want to call 3 times for button click?
Why not put them all together?
Any how you can use variable as isAlertToBeShown= false and after pushing data make it has true. finally check the variable is true or false.