LOADPAGE - Parsing JSON Request failed, status 200 - node.js

[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

Related

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

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/)

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/

Bad Request error in uber api

I've been trying to get the uber price estimates endpoint working, but I'm stuck on an error that leads me to a blank page saying, "Bad Request." The console also says "callback not a function" but I can't seem to find out what is wrong.
My route:
// Get an upfront fare before requesting a ride
app.get('/v1.2/estimates/price', function(request, response) {
// extract the query from the request URL
var query = request.query;
// if no query params sent, respond with Bad Request
if (!query || !query.lat || !query.lng) {
response.sendStatus(400);
} else {
uber.estimates.getPriceForRouteAsync( {
"product_id": "33de8094-3dc4-4ca9-8f67-243275f57623",
"start_latitude": "38.9597897",
"start_longitude": "-94.60699369999999",
"end_latitude": "39.010969",
"end_longitude": "-94.61509899999999"
})
.then(function(res) {
log(res);
})
.error(function(err) {
console.error(err);
});
}
});
Any help is appreciated.
Please check out the README for node-uber. The method does not take a JSON object but the arguments in the method call:
uber.estimates.getPriceForRouteAsync(38.9597897, -94.606994, 39.010969, -94.615098)
.then(function(res) { console.log(res); })
.error(function(err) { console.error(err); });
Also, the product ID is not needed as the /estimates/price endpoint returns an array of estimates for each product.

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