alega
alega

Reputation: 97

Insert variables into $.post within a function

i'm writing a function to send $.post show please how to correctly insert variables into object depending if they are set. here is what i'm trying to do:

function SendCommand(Command, QuestionId, Attr) {   
   $.post('/survey/admin/command',
    {
     'Command': Command,
     if (QuestionId) 'QuestionId' : QuestionId,
     if (Attr) 'Attribute' : Attr
    }
   );   
 }

Thanks!

Upvotes: 1

Views: 121

Answers (4)

Quincy
Quincy

Reputation: 4433

Try this(untested)

function SendCommand(Command, QuestionId, Attr) { 
    var data = {};
    data['Command'] = Command;
    if (QuestionId) data['QuestionId'] = QuestionId;
    if (Attr) data['Attribute'] = Attr;
   $.post('/survey/admin/command',data  );   
 }

Upvotes: 0

CarlosZ
CarlosZ

Reputation: 8679

You can always create your data before the $.post call

var data = {
 'Command': Command
};

if (QuestionId) {
  data.QuestionId = QuestionId;
}
if (Attribute) {
  data.Attribute = Attribute;
}

$.post("your/url", data);

Upvotes: 3

MillsJROSS
MillsJROSS

Reputation: 1239

This is quick way to implement this...

$.post('/survey/admin/command',
  {
   Command: Command,
   QuestionId: QuestionId || undefined,
   Attribute: Attribute || undefined
  }
);

The biggest downfall to this method, though is that there are certain values (such as zero or an empty string) that are false. So this is not a catch all method.

Upvotes: 1

Jordan
Jordan

Reputation: 1238

If there's the possibility of null values, I'd go with:

$.post('/survey/admin/command',
  {
   'Command': Command,
   'QuestionId' : QuestionId ? QuestionId : undefined,
   'Attribute' : Attribute ? Attribute : undefined,
  }
);

Otherwise, I think jQuery will ignore undefined params.

Upvotes: 0

Related Questions