0

I tried looking but didn't find anything specific to my problem. I am trying to return a JSON object to a client-side AJAX call but the value keeps saying undefined.

front-end callAdmin.js makes the AJAX call to /retrieveRandomQuestion

now back-end questionAnswer.js gets called:

router.post('/retrieveRandomQuestion', function(req, res) {
    console.log('retrieveRandomQuestion called');
    db.retrieveRandomQuestion(req);
});

// fyi app.js has global variable

db = new database();

... now on to dbLayer.js

var db = function() {
  // retrieve a random question from the database
    this.retrieveRandomQuestion = function(req) {
        question.count().exec(function(err, count) {
            var random = Math.floor(Math.random() * count);

            question.findOne().skip(random).exec(
                function (err, result) {
                    console.log(result);
            });
        });
    };
}

console.log(result) shown above in dbLayer shows the object but when I try to access the object in questionAnswer.js db.retrieveRandomQuestion(req); it prints undefined.

Help!

  • can you update with your client-side code, which is making the AJAX call. – Nivesh Mar 23 '16 at 04:42
  • What is parameters AJAX sent? – DinhNguyen Mar 23 '16 at 04:42
  • if you just need to send back random Question, you need not send a POST request, you can simply do that via GET request. Besides, there is no use of sending `req` to the db operation function, instead you can use call back function, which would send the json response once db operation is complete. – Nivesh Mar 23 '16 at 04:45

0 Answers0