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/
Related
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/)
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
[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
Im trying to request a status of a user, with a POST from node.js to a PHP file.
My issue is that the webservice Im calling is VERY slow to reply(4 sec), so I think the .then finishes before the 4 sec, and therefore returns nothing. Got any idea if i can extend the time for the request?
requestify.post('https://example.com/', {
email: 'foo#bar.com'
})
.then(function(response) {
var answer = response.getBody();
console.log("answer:" + answer);
});
I am not that knowledgeable on requestify but are you sure you can use post to a https address? In the readme only requestify.request(...) uses a https address as an example. (see readme)
One tip I can definitely give you though is to always catch your promise:
requestify.get(URL).then(function(response) {
console.log(response.getBody())
}).catch(function(err){
console.log('Requestify Error', err);
next(err);
});
This should at least give you the error of your promise and you can specify your problem.
Each call to Requestify allows you to pass through an Options object, the definition of that object is described here: Requestify API Reference
You are using the short method for POST, so I'll show that first, but this same syntax will work for put as well, notice that get, delete, head do not accept a data argument, you send url query parameters through the params config property.
requestify.post(url, data, config)
requestify.put(url, data, config)
requestify.get(url, config)
requestify.delete(url, config)
requestify.head(url, config)
Now, config has a timeout property
timeout {number}
Set a timeout (in milliseconds) for the request.
So we can specify the a timeout of 60 seconds with this syntax:
var config = {};
config.timeout = 60000;
requestify.post(url, data, config)
or inline:
requestify.post(url, data, { timeout: 60000 })
So lets put that together now into your original request:
as #Jabalaja pointed out, you should catch any exception messages, however you should do this with the error argument on the continuation.
(.then)
requestify.post('https://example.com/', {
email: 'foo#bar.com'
}, {
timeout: 60000
})
.then(function(response) {
var answer = response.getBody();
console.log("answer:" + answer);
}, function(error) {
var errorMessage = "Post Failed";
if(error.code && error.body)
errorMessage += " - " + error.code + ": " + error.body
console.log(errorMessage);
// dump the full object to see if you can formulate a better error message.
console.log(error);
});
I probably have some issues with the asyncness of Node.js.
rest.js
var Shred = require("shred");
var shred = new Shred();
module.exports = {
Request: function (ressource,datacont) {
var req = shred.get({
url: 'ip'+ressource,
headers: {
Accept: 'application/json',
},
on: {
// You can use response codes as events
200: function(response) {
// Shred will automatically JSON-decode response bodies that have a
// JSON Content-Type
if (datacont === undefined){
return response.content.data;
//console.log(response.content.data);
}
else return response.content.data[datacont];
},
// Any other response means something's wrong
response: function(response) {
return "Oh no!";
}
}
});
}
}
other.js
var rest = require('./rest.js');
console.log(rest.Request('/system'));
The problem ist if I call the request from the other.js I always get 'undefined'. If I uncomment the console.log in rest.js then the right response of the http request is written to the console. I think the problem is that the value is returned before the actual response of the request is there. Does anyone know how to fix that?
Best,
dom
First off, it is useful to strip down the code you have.
Request: function (ressource, datacont) {
var req = shred.get({
// ...
on: {
// ...
}
});
}
Your Request function never returns anything at all, so when you call it and console.log the result, it will always print undefined. Your request handlers for the various status codes call return, but those returns are inside of the individual handler functions, not inside Request.
You are correct about the asynchronous nature of Node though. It is impossible for you to return the result of the request, because the request will still be in progress when your function returns. Basically when you run Request, you are starting the request, but it can finish at any time in the future. The way this is handled in JavaScript is with callback functions.
Request: function (ressource, datacont, callback) {
var req = shred.get({
// ...
on: {
200: function(response){
callback(null, response);
},
response: function(response){
callback(response, null);
}
}
});
}
// Called like this:
var rest = require('./rest.js');
rest.Request('/system', undefined, function(err, data){
console.log(err, data);
})
You pass a third argument to Request which is a function to call when the request has finished. The standard Node format for callbacks that can fail is function(err, data){ so in this case on success you pass null because there is no error, and you pass the response as the data. If there is any status code, then you can consider it an error or whatever you want.