javascript - How to send data to MongoDB that is calculated after page loads? -


i using node.js express , mongodb.

i have page, '/score' calculates user's score quiz taken on previous page. '/score' route below:

app.get('/score', stormpath.getuser, function(req, res) {     var quiz = req.session.mostrecentquiz;     db.collection('quizzes').find(quiz).toarray(function (err, docs) {         assert.equal(err, null);         var quiz;           docs.foreach(function (doc) {             quiz = doc.quiz;         });         res.render('score', {quiz: quiz});     });     db.collection('users').update({user: req.user.username}, { $set: {"mostrecentquiz": quiz } }, function (err, result) {         if (err) throw err;         console.log(result);     } ); }); 

after getting quiz answers db, use client-side javascript on /score page calculate user's score , report user. however, same score mongodb, not sure how best accomplish that.

can use ajax accomplish this, or better redirect new page?

if you're using express, simplest way define route updating score. can send data server via ajax. in order parse request parameters install body-parser module.

server:

var bodyparser = require('body-parser') app.use(bodyparser.urlencoded({ extended: true })); app.use(bodyparser.json());  app.put('/score', stormpath.getuser, function (req, res) {    console.log(req.body); // there should received data    // save database   db.collection('yourcollection').updateone(       {}, // query updating data in wished field       function(err, results) {         if(err) { return res.json(err); };          return res.json(results);    }); });  

client - if you're using jquery:

$.ajax({     url: '/score',     type: 'put',     contenttype: 'application/json',     data: {'score':1000}, // put here data send server     success: function(data){         console.log(data);     } }); 

some documentation:

mongodb update: https://docs.mongodb.com/getting-started/node/update/

jquery ajax: https://api.jquery.com/jquery.ajax/


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -