1

I have this line of Javascript jQuery code

$.post('/blah', { comment_id: 1, description: ... });

However, what I really need is the ability to change comment_id to something else on the fly, how do I make that into a variable that I can change?

EDIT

Clarification, I meant changing the value of comment_id to say photo_id, so the left side of the assignment.

3 Answers 3

7

Use a javascript variable: https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals

 var commentId = 1;
 $.post('/blah', { comment_id: commentId, description: ... });

EDIT:

var data = {}; // new object
data['some_name'] = 'some value';
data['another_name'] = true;
$.post('/blah', data);  // sends some_name=some value&another_name=true

EDIT 2:

$.post('/blah', (function () { var data = {}; // new object
  data['some_name'] = 'some value';
  data['another_name'] = true;
  return data;
}()));
Sign up to request clarification or add additional context in comments.

2 Comments

Crap, I'm thinking not per this article unethicalblogger.com/2008/03/21/…
Yeah, that made it hard to read and simply just moved the code. I'll stick with your first solution, thanks.
2
function doIt(commentId) {
  $.post('/blah', { comment_id: commentId, description: ... });
}

Thanks to the clarification from Cameron, here's an example that does what the OP actually asked for, that is to make a property name in the object dynamic.

function doIt(name, value) {
  var options = {description: '', other_prop: ''};
  // This is the only way to add a dynamic property, can't use the literal
  options[name] = value;
  $.post('/blah', options);
}

Comments

1

Assign the object to a variable first so that you can manipulate it:

var comment_id = 17;
var options =  { description: ... };
options[comment_id] = 1;  // Now options is { 17: 1, description: ... }

2 Comments

This is not what OP asked for, should say options['comment_id'] = comment_id, shouldn't it?
@Juan: I thought the OP wanted to change the attribute (not the value), and it turns out I was right (though I agree the question was originally ambiguous)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.