Richard
Richard

Reputation: 1158

Jquery ajax - passing params as variable

I have an ajax call (using a blackberry webworks api [but I don't think that bit is relevant]).

At the moment I'm sending params like this:

params: {
   user: userId,
   sid: sessionKey,
   db: dbId,
   urn: activeRecord
},

I'd like to build the params (sometime I won't need them all, and I don't want to send blank data).

However if I try to build a string and send that the program errors.

EG:

The error occurs if I try and build the params like this:

var myParams ="";

if(userId != ""){
   myParams != "user:" + userId + ",";
}

if(sessionKey != ""){
   myParams != "sid:" + sessionKey + ",";
}


myParams = myParams.slice(-1);

Then try add params in the call like so:

params: { myParams },

Any thoughts?

Upvotes: 0

Views: 116

Answers (3)

Richard
Richard

Reputation: 1158

Thanks for the help guys, appreciate it, finally figured it out. The problem is I'm trying to add variables into an object which just doesn't work. The way to do it is this:

//create the object
var myParams = {};

//add variables (if statements are fine here)
myParams.user = userId;
myParams.sid = sessionKey;

Then later on when you need to use it you can add it in like so:

params: myParams,

Upvotes: 0

Alex
Alex

Reputation: 7374

Is the != your problem?

if(userId != ""){
   myParams = "user:" + userId + ",";
}

if(sessionKey != ""){
   myParams = "sid:" + sessionKey + ",";
}

Upvotes: 0

c.hill
c.hill

Reputation: 3233

I think this is what you're after:

$.ajax({
    type: 'GET',
    url: 'INPUT URL HERE',
    data: {
        user: userId,
        sid: sessionKey,
        db: dbId,
        urn: activeRecord
    },
    success: function(response)
    {
        // Do stuff.
    }
});

Upvotes: 2

Related Questions