How to do AJAX POST call in express.js file in handlebar? - node.js

I am trying to send/update data to mongoDB database via AAJAX call but the command is not reaching theere. I have tried debugging using alert in between the code but the command is not reaching there. Means AJAX call doesn't get executed.
Below is my AJAX POST request code:
var text = "Done";
var data = {
selectedValue: text
}
$ajax({
method: 'POST',
url: '/update-sources',
dataType: 'text/json',
data: data,
success: function(data){
console.log(data);
alert("Working!!")
}
});
And Below is the /update-sources route code:
router.post('/update-sources', function(req, res, next) {
console.log("/Update-Sources")
User.findOneAndUpdate({email: req.user.email}, {$set:{status:data.selectedValue}}, {new: true}, (err, doc) => {
if (err) {
console.log("Something wrong when updating data!");
}
else
{
res.render('taskswriter');
console.log(doc);
return "Great Working!";
}
});
});
What mistake I am doing?

Would be great if you shared browser's console output, but trying to execute attached client-side snippet, I got the following error:
VM219:7 Uncaught ReferenceError: $ajax is not defined
at <anonymous>:7:1
You've got a typo there - it should be $.ajax as you are accessing a function from within jQuery namespace (https://api.jquery.com/jQuery.ajax/)

Related

Problem with redirect using 'fetch' from frontend page

I am using the following JS in a webpage to send information to a Node.js server upon 'clicking' on an image in the webpage, I am having trouble with the 'redirect' once the 'fetch' is executed:
fetch('/members/pages/callup', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({name: splits[1], presence: available, str: 'Some string: &=&'})
})
.then(function(res) {res.json()})
.then(function(res) {
if(res.response) {
redirect: window.location.replace("/members/pages/" + splits[1]);
} else {
alert("Error in the response");
}
})
.catch(function(err) {
alert("Error in the fetch call..." + err);
})
The fetch seems to properly send the 'body' data to the server. However I am getting the following error: "Error in the fetch call...TypeError: Cannot read property 'response' of undefined"...
The server performs a database call using the information sent by the frontend, and I thought all I needed to do was to send a "200 (OK)" response back...here is the server code:
app.post('/member/pages/callup', jsonParser, function (req, res) {
console.log("I RECEIVED FROM CLIENT THE FOLLOWING:");
console.log(req.body); //works fine, prints output from frontend 'fetch' to console...
db.lookupMember(req.body.name)
.then(function(foundUser) {
console.log('Async success!', foundUser); //works fine, prints database info to console...
if (typeof foundUser != "undefined") {
res.sendStatus(200); //trying this to 'reply' back to 'fetch' in frontend...is this not correct?
} //'foundUser' is NOT'undefined'...
})
.catch(function(error) {
console.log('UNABLE TO RETRIEVE MEMBER INFORMATION FROM THE DATABASE...' + error);
res.redirect('/'); //route to splash page...
});
})
Any suggestions appreciated, this has gone from a minor irritant to a major problem. I thank you in advance.
There are few issues in the code. If fixed, code should work fine.
You forgot to return res.json() from the function at one place. Make it return res.json() and it will work fine (Inside fetch, 1st then). Due to not returning, res is undefined which is giving the error
You are trying to use res.response but res is not send as a proper json from node server. This will fail at res.json(). You should be doing something like res.send({response: true})
After the if loop in server there is syntax error. It needs to be redirect = instead of redirect:. Also redirect is not declared anywhere which. (Note: you might not need redirect variable here, simply window.lo... should also work)
Note: Have updated the original answer after having the discussion with OP

Ajax success and error handlers not working with nodejs

For some reason, the success and error handlers of my ajax request is not working as expected.
My node server performs correctly and gives me the right results, but whatever is in the error section of my ajax request executes regardless.
I checked other posts and they seem to be doing the same thing I am. I can't figure out what's happening.
My ajax code:
$.ajax({
url: path,
method: 'POST',
dataType: 'JSON',
data: items,
success: function(response)
{
alert('Tweety Logs sent successfully.')
},
error: function(err)
{
alert('Tweety Logs not sent.')
}
});
The function in my server:
function log(req,res)
{
var breed = req.body.breed;
var list = req.body.logs;
try {
fs.appendFileSync("Logs/log.dat", JSON.stringify(breed) + "logs:\r\n");
for(let i = 0; i < list.length; i++)
{
fs.appendFileSync("Logs/log.dat", JSON.stringify(list[i]) + "\r\n");
console.log('Added to Logs/log.dat - ' + JSON.stringify(list[i]));
}
res.sendStatus(200);
}
catch (err) {
console.log('Error writing to the file: ' + err.message)
res.sendStatus(500);
}
}
The error bit of ajax gets called everytime even if it's successful.
Any idea why?
If you add console log in your server code it it won't be a json response. You need to add json data to your res.send instead of console.log
And remove console.logs
It been awhile I used Ajax last but you can try out axios or fetch they will make your life much easier.
Axios handle error better by using the catch block.
Check this links for more help and details.
https://alligator.io/js/axios-vanilla-js/
https://alligator.io/js/fetch-api/

LOADPAGE - Parsing JSON Request failed, status 200

[REGISTER SHIFT/ ASSIGNMENT FORM]
Here is my form, let me describe it; it register next week working hours, I design there are 2 cases: add new and edit in the same form.
When user select an employee, if not register shift yet, we let user register for this employee, if shift is registered already, user can edit in the same form. And I think it will be better not refresh the page, every time user change employee, the form just update and let user add/edit then submit it by post method.
I searched the web, and found a recommendation for ajax/jQuery.
Any more recommendations for me? I've just learn Nodejs/Express with PostgreSQL database.
I am trying to use ajax to load mypage from post event, I call error function in ajax to see what the error is and get:
Parsing JSON Request failed. Status 200.
I'm using NodeJS Express Server, EJS view engine, body-parser, postgresql db.
pool.connect((err, client, release) => {
if (err) {
return console.error('Error acquiring client', err.stack)
}
client.query(
'SELECT * FROM "Employee"', (err, result) => {
release()
if (err) {
res.end();
return console.error('Error executing query', err.stack);
}
console.log(typeof(result));
res.type('json');
res.render("index", {emplist : result});
res.end();
})
})
My ajax function:
$.ajax({
url: "/addshift",
type: "POST",
data: JSON.stringify(employee),
dataType: "application/json",
contentType: 'application/json',
complete: function () {
console.log("go into complete !");
},
success: function (response) {
console.log(response);
console.log("go into success !");
},
error:function(x,e) {
if (x.status==0) {
alert('You are offline!!\n Please Check Your Network.');
} else if(x.status==404) {
alert('Requested URL not found.');
} else if(x.status==500) {
alert('Internel Server Error.');
} else if(e=='parsererror') {
alert('Error.\nParsing JSON Request failed. ' + x.status);
} else if(e=='timeout'){
alert('Request Time out.');
} else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
let's see:
"I am trying to use ajax to load mypage from post event"
Ok, so I suppose you want to get a fully formed HTML page from your $post.
Then, I see:
console.log(typeof(result));
res.type('json');
res.render("index", {emplist : result});
res.end();
res.render will return HTML, this is good for your goal. BUT, you're also specifying a JSON type with res.type. This is causing the error. HTML is not JSON clearly.
Furthermore, you don't need the call to res.end(). res.render() will finish the transaction correctly on its own, res.end is for errors or unexpected conditions.
Your ajax code is ok, but if you're trying to update an html component, like a select, you need to do that manually using the response from ajax, like so:
$("#selectElem").html(response);
Furthermore, you should check your result object from the SELECT * FROM EMPLOYEE query is correctly formatted as proper JSON

Node Request inside request with cookie

I am using node request var request = require(“request”); in my config node to do a POST request and in response get a Cookie which need to be referred in all rest of requests.
I tried enabling COOKIE JAR that works fine if i chain my request under first request but I want to call rest of requests like GetList from custom node.
I tried toughcookie (file cookie) not working when i add var j = request.jar(new FileCookieStore(‘cookies.json’));
node stop working with no error.
Below is my config node, code using which I am getting Cookie.
function myAuthNode(n) {
RED.nodes.createNode(this,n);
this.username=n.username;
this.password=n.password;
this.connect=function(){
//TODO-NG need to make URL configurable
request.post({url: "http://localhost:8080/api/method/login", qs: {usr: this.username, pwd: this.password}}, function(err, res, body) {
if(err) {
return console.error(err);
}
console.log("HERE IF I PUT REQUEST Works fine");
console.log("CAN WE PASS ANOTHER REQUEST here from calling SOURCE to execute here?");
});
};
}
Here in this custom node I am calling
// The main node definition - most things happen in here
function GetListNode(n) {
// Create a RED node
RED.nodes.createNode(this,n);
console.log('I am called');
//using auth config now you are connected, tell me what is needed?
this.authConfig=RED.nodes.getNode(n.auth);
//connect to config and do auth
this.authConfig.connect();
//THIS ALWAYS FAILS due to cookie not found where as I enable request JAR
request.get({url: "http://localhost:8080/api/resource/Project"}, function(err, res, body) {
if(err) {
return console.error(err);
}
console.log("Response body:", body);
});
}
Please suggest how to handle cookie in request so that all requests after auth works fine?
Can we pass a request definition to another request for execution inside it or how Cookie can be handled ?
I resolved this by doing below inside GetListNode(), i shifted second request inside the call:
this.authConfig.connect(function(){request.get({url: "http://localhost:8080/api/resource/Project"}, function(err, res, body) {
if(err) {
return console.error(err);
}
console.log("Response body:", body);
});});
and inside config node i did below, added a function parameter and called that passed function, WORKED fine :):
this.connect=function(f){
//TODO-NG need to make URL configurable
request.post({url: "http://localhost:8080/api/method/login", qs: {usr: this.username, pwd: this.password}}, function(err, res, body) {
if(err) {
return console.error(err);
}
f.call();
});
};

Nodejs inserting data to mongodb. It takes too much time

Hi i am developing nodejs application. I am inserting data to mongodb but my page always in 'loading' mode. But strange thing is my data inserted to mongodb immediately but page load not stopping. My code is shown below:
app.post('/Management/Post/New',function(req, res){
new Post({
title:req.body.post.title,
body:req.body.post.body,
keywords:req.body.post.keywords
}).save(function (err, docs){
if(err) {
return res.render(__dirname + "/views/createpost", {
title: 'Yeni Gönderi Oluştur',
stylesheet: 'postcreate',
error: 'Gönderi oluşturulurken bir hata ile karşılaşıldı'
});
}
console.log('Gönderi oluşturuldu');
});
});
Have no idea.
You only send a response when there is an error. If there's no error, you server never sends anything back: that's why the page seems to always be loading.
You need to send a response when you have no error, like this:
.save(function (err, docs){
if(err) { // Executed when there was an error with Mongo
return res.render(...);
} else { // Executed when everything is fine
return res.render(...);
}
});
You aren't handling the success scenario except for a console.log. You need a res.render() or res.redirect() on success, not just error

Resources