views:

25

answers:

1

How can I assign a variable to content attr of dojo.xhrPost dynamically ? Below is the code and some explanation for my scenario:

Code with hard coded values for content

dojo.xhrPost({
url: /esturl/,
handleAs : "text",
content : {INST1 : '{"0001" : "aa"}',
            INST2 : '{"0002" : "bb"}',
            INST3 : '{"0003" : "cc"}'}
load : load(data),
error : error
});

The number of INST in Content attr can be minimum 1 and max 6, as of now I am hard coding 3 pairs there. But I want to have one var like buildJason

var buildJson = function (){
}

And this var will populate dynamic value to content attr. I am having "0001" "aa" values from

var element = dojo.query('input:checked');
element.id;

But everytime user checks different box than depending upon user selection values for content attr should be dynamically populated, any suggestion as to how this can be achieved ?

Update

After using approach suggested by CastroXXL, am getting following error message on firebug.

missing : after property id
var myContent = {};\n

Any suggestions as to how I can deal with it ?

A: 

To build a JSON object you can use the code below.

var buildJson = function (name, value){
  var myJson = {};

  myJson[name] = value;

  return myJson;
};//Forgot the semicolon. 

A script that would put this together could like the following.

var myContent = {};
var count = 0;

dojo.query("input:checked").forEach(function(input){
  myContent['INST' + count] = buildJson(input.id, input.value);

  count++;
});

dojo.xhrPost({
  url: /esturl/,
  handleAs : "text",
  content : myContent,
  load : load(data),
  error : error
});

EDIT: You get that error when you do something like the following.

var test = {
  var myContent = {};
};

You can either close the JSON object before like:

var test = {};
var myContent = {};

or you can make the myContent work in your JSON like:

var test = {
  myContent:{}
};
CastroXXL
I am getting `missing : after property id var myContent = {};\n on firebug after using the approach you suggested, not sure how to move forward, any suggestion CastroXXL
Rachel
That error usually happens when you are inside of a JSON object already. It is most likely the code right before that line that is causing the issue. Could you show that?
CastroXXL
Thank you CastroXXL, I was able to get it work.
Rachel