flakeyjake flakeyjake - 5 months ago 17
MySQL Question

JQuery Post to NodeJS return MySQL value gives undefined?

So I'm trying to make a basic query to my database and pull back one value with JQuery.

JQuery Code:

function getTokens(user, cb) {

$.post("/getTokens", {username: user}, function(data) {
return cb(data);


app.post('/getTokens', function(req, res) {
connection.query('select tokens from users where username = "' + req.body.username + '"', function(err, rows, fields) {
if (err)
else {


I want to store the returned value in a string. In the callback function, if I console.log or alert the 'tokens' parameter it correctly shows it, however if I just return it like I have below, 'tokens' is undefined when I apply it to the #username_field. Like so:

totalTokens = getTokens(username, function(tokens){
// console.log(tokens); why does this work, but the line below doesn't?

return tokens;


$('#username_field').text('Tokens: ' + tokens);

If anyone can help me get the returned value 'tokens' onto my #username_field that would be awesome. Any suggestions would be helpful, it's driving me nuts that it keeps returning undefined.


The node part looks fine.

Do this instead for your front end. Get rid of the return and the variable, you don't need that:

getTokens(username, function(tokens){
$('#username_field').text('Tokens: ' + tokens);

Fyi, Your code is using variables incorrectly. The jquery portion would use totalTokens, not tokens.