AJAX post data almost saving to the db? - javascript

Testing the modules, the AJAX is posting properly in the browser's console.log, and the Node.js/express4 mongoose .save method is saving properly into MongoDB (testing with Postman - REST Client)
For some reason, the AJAX post data has yet to make it to the db, though it accurately logs the data..
$(document).ready(function(){
$('#SubmitBtn').click(function() {
var message = $( "#message" ).val();
console.log(message); // logs as the "user's message"
var AjaxPostData = {'message' : message};
console.log(AjaxPostData); // logs as [object Object]
// make an ajax call
$.ajax({
dataType: 'json',
data: AjaxPostData,
type: 'post',
url:"http://localhost:4200/api/v1/stories",
success: foundAllSuccess,
error: foundAllFailure
});
console.log(AjaxPostData.message); // logs as the "user's message"
});
});
Express4 routing:
var router = express.Router(); // an instance of the express Router
var Story = require('./app/models/story'); // load the mongoose model
router.route('/stories')
// create a story (accessed at POST http://localhost:4200/api/v1/stories)
.post(function(req, res) {
var story = new Story(); // create a new instance of the Story model
story.message = req.body.message; // set the message, from the request
console.log(req.body.message); // logs with Postman, yet the ajax post
// save the story, and check for errors
story.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Story "' + story.message + '" Created' });
});
})
app.use( '/api/v1', router ); // all of the routes are prefixed

Replace data: AjaxPostData,
With data : JSON.stringify(AjaxPostData),
I dont believe the data is being passed correctly and thats why it sends at [Object object]

Turns out that the ajax click event needed e.preventDefault(); or return false;
$('#SubmitBtn').click(function(e) {
e.preventDefault();
// do something
});
$('#SubmitBtn').click(function() {
//do something
return false;
});
Either work in this case..though here's a great post on the differences: event.preventDefault() vs. return false

Related

Trying to pass an id to nodejs with jquery

I am trying to set up friend requests on my app. Since I know who the user is who is logged in (the requesting friend) via req.user, I need to know who's profile the logged-in user is looking at (the receiving friend). Since I'm using pug as a template engine, I couldn't find a way to pass the receiving friend's id as an html id, so I saved it as a title attribute with this:
button.btn.btn-primary.btn-block#addFriendBTN(title = `${user.id}`) Add friend
My jquery is this. When I console log friendId it does capture the right id and I've checked it's type of as string to make sure.
$('#addFriendBTN').on('click', function() {
var friendId = $(this).attr('title');
$.ajax({
method: 'POST',
url: '/users/' + friendId,
data: {
recevingId: friendId
},
success: function() {
$('#addFriendBTN').hide();
},
error: function(err) {
console.log("err is " + err);
}
});
});
In my server-side js in my users file, I have this post route:
router.post('/:id', isLoggedIn, function(req, res) {
var receivingId = req.body;
console.log("User Id is " + receivingId);
});
But the console log (in the browser) is giving me an error so it's not even getting tot he server-side js.
The error I receive is a 500 internal server error and then err is [object object]. Any thoughts on why this isn't working?
you are getting the body object, try this:
var receivingId = req.body.recevingId;

session data getting stored every time

Below is the API that basically stores data in session if not already present then returns an empty JSON, otherwise sends the session data stored corresponding to that mail:
app.use('/session', function(req, res) {
if (req.body.email in req.session) {
console.log("user data already available");
res.send(req.session[req.body.email]);
} else {
req.session[req.body.email] = {};
req.session[req.body.email]["email"] = req.body.email;
req.session[req.body.email]["gender"] = req.body.gender;
req.session[req.body.email]["dbname"] = req.body.dbname;
console.log("user session stored");
res.send({});
}
});
Below is the ajax call that I am making from my application. It is a cross domain call and I have set the response header accordingly.
$.ajax({
url: 'url/session',
type: "POST",
crossOrigin: true,
data: {
"email": "email",
"gender": "all",
"dbname": "dbname"
},
success: function(data) {
console.log("inside session api call success");
console.log(data)
}
});
});
Now the problem is that if I hit the API using postman, it works fine but when I use that in my application, it overwrites the session every time and returns empty json. What am I doing wrong?
edit : Figured out that each time ajax call is happening, past session data gets deleted for all emails ids.session value gets reset but still unable to figure out why this is happening.

Update a p element from a nodejs function

I need to send a value from a input form to a nodejs server, which triggers a calculation with this value and needs to update an p element with the result of the calculation on the client side.
How can this be done?
This is what i have:
//Server side:
app.post('/calculate/:id', function(req, res){
var title = 'Tax Calculation';
var tax= taxcalculation(req.params.id);
res.render('index', {
title: title,
tax: tax,
});
});
//Client side:
var income= document.getElementById("income");
var tax = document.getElementById("tax")
$(income).on('change', function() {
console.log("changed");
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function() {
$('#tax').html('<%= tax %>');
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});
});
Okay, so you don't give a lot of data, but this sounds as simple as sending a response with the results to the client side in your Node web service that does the calculations and append the result to the P element
Your server code to handle the ajax call should output a json response which will contain the content for the <p>. It should not re-render the whole index page. I don't do a lot of node.js so I'll leave that for you to figure out.
The ajax success function should accept a response as a parameter, and then operate on that response.
Assuming the server response to this ajax request is of the format {"tax": 15.99}:
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function(response) {
if (response.tax || response.tax === 0) {
$('#tax').html(response.tax);
}
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});

passing variable from jQuery ajax to nodejs

i am trying to pass a variable from jQuery to nodejs, but i am not getting the right results, nodejs returns [object Object]. how can it return a string variable on nodejs side.
$('.test').click(function(){
var tsId = "Hello World";
alert(tsId);
console.log(tsId);
$.ajax({
'type': 'post',
'data':tsId,
'url': '/test/testing',
'success': function (data) {
alert(data);
}
})
});
router.post('/testing', function(req, res) {
var tsID = req.body;
console.log("stsID "+tsID );\\ outputs [object Object]
});
I recommend you to use this way:
You should pass an object in ajax data, which contains your Hello World string.
$.ajax({
type: 'post',
data:{str:tsId},
url: '/test/testing',
success: function (data) {
alert(data);
}
});
In node.js file use this:
router.post('/testing', function(req, res) {
var tsID = req.body;
console.log("stsID "+tsID.str );
});
Try console logging tsID.data or tsID.tsId. What do you get? What do you get if you throw a debugger before your console log and write "tsID" in the console?

Array is flattened when it's sent through AJAX jQuery request

I have the following endpoint written in Express, using the body-parser middleware.
app.post("/api/poll/new",api.NewPoll);
api.NewPoll = function(req,res){
if(!req.body) return res.status(400).send("MISSING BODY");
console.log(req.body,typeof(req.body));
if(!req.body.name) return res.status(400).send("MISSING NAME");
if(!req.body.options) return res.status(400).send("MISSING OPTIONS");
//rest of the endpoint goes here
};
The data that the endpoint expects looks like this:
{
"name":"Poller",
"options":[
{
"name":"Jojo's Bizarre Adventure",
"desc":"A great show"
},
{
"name":"Bakemonogatari",
"desc":"A real good show"
},
}
When I send this data through Postman, everything works. req.body.options exists and is an array. However, when I do the exact same thing in a jQuery AJAX call, the result is signficantly different:
var payload = {
name:"Poller",
options:g.newPollInfo
//g.newPollInfo contains the same array
}
$.ajax({
method:"POST",
url:"/api/poll/new",
data:payload,
success:function(data){
console.log(data);
},
error:function(req, status, error){
console.log(req,status,error);
}
});
I get a 400 error, reporting missing Options. The printed req.body looks like this:
{ name: 'Poller',
'options[0][name]': 'Jojo'\s Bizarre Adventure',
'options[0][desc]': 'A great show',
'options[1][name]': 'Bakemonogatari',
'options[1][desc]': 'A real good show' } 'object'
I have never had this problem before. The problem is not in express, as a request through Postman using the same data and it works. The only problem I can think of lies in the fact that the request is made from an iframe serviced through a secure connection, but that doesn't make sense.
I have no idea what causes this error.
According to both these questions, the problem is solved specify the header type on the AJAX Request and stringify.
$.ajax({
method:"POST",
url:"/api/poll/new",
data:JSON.stringify(payload),
contentType:"application/json",
success:function(data){
console.log(data);
},
error:function(req, status, error){
console.log(req,status,error);
}
});

Categories

Resources