Antonio Laguna
Antonio Laguna

Reputation: 9292

Evaluating params before serializing

I'm building some functions to retrieve data whether you supply some params or don't. It will be used mostly with a geolocator function. Since it may provide (or not) the location, the function should be able to handle that but I'm not able to do that.

Here is the code:

function getData(position,line,limit,attach){
        var JSONurl = 'getter.php';
        var params = [
            {   get: "stations",
                line: line,
                limit: limit,
                lat : position.coords.latitude,
                lng : position.coords.longitude
            }
        ];            
        console.log($.param(params));
    }

But it happens two things, $.param(params) give me undefined and also, when no position is supplied (so position is null) it gives me an error that it's not able to retrieve .cords o a null value (which is good).

How could I solve this?

Upvotes: 0

Views: 64

Answers (1)

Ortiga
Ortiga

Reputation: 8814

Not sure if it's the best solution but you can go for something like

var params = [
            {   get: "stations",
                line: line,
                limit: limit,
                lat : (function(){
                    try {
                        return position.coords.latitude;
                    }
                    catch(e){
                        return null;
                    }
                })(),
                lng : (function(){
                    try {
                        return position.coords.longitude;
                    }
                    catch(e){
                        return null;
                    }
                })()
            }

Of course, you can go for a non-anonymous solution too

Upvotes: 1

Related Questions