Mumfi Mumfi - 1 year ago 60
Javascript Question

How check which variable is sent to a function in Javascript

I have a Javascript AJAX function that can send some data (to a MongoDB database)f
. The database only consists of one document which keeps track of the total amount of questions answered and also the number of questions answered correctly.

The function can take either of these numbers (updated in different places in the code), but how do I check which number it is inside of the function? It would look something like this:

function updateQuestionsProgress(number) {
//TODO Check which of the two numbers is sent
type: "POST",
url: "/statistics/quick_test",
data : theNumber,

error:function(msg, string){


Knowing which number it is, I could then update it accordingly in that URL middleware.

Am I better of just doing two different functions instead? Seems very inconvenient if you have a very large database and you just want to update part of a document.

108 108
Answer Source

What you need is the caller of the function to tell you which number it is. You can send a string a bool flag (since it's just two options), or an object.

function updateQuestionsProgress(dataObj) {
//TODO Check which of the two numbers is sent
    type: "POST",
    url: "/statistics/quick_test",
    data : dataObj,

When you call updateQuestionsProgress(dataObj) you can pass whatever object you like to the function. E.x. var dataObj = {"answers" : 5, "correct_answers": 3} and anything else you need.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download