views:

41

answers:

2

I'm thinking this is not possible but I would like some insight as to why. I want to do something like this:

var pVals = {
    ob1: "postvar1",
    ob2: "postvar2",
    ob3: "postvar2"
};

$.post("php/dosomething.php",{pVals.ob1:"object 1", pVals.ob2:"object 2", pVals.ob3:"object 3"});

I get an error along the lines of:

missing : after property id

Thanks for the help.

+1  A: 

You can get the same end result, you just can't do it in one statement:

var pVals = {
    ob1: "postvar1",
    ob2: "postvar2",
    ob3: "postvar2"
};

var obj = {};
obj[pVals.ob1] = "object 1";
obj[pVals.ob2] = "object 2";
obj[pVals.ob3] = "object 3";
$.post("php/dosomething.php", obj);

This is because the "keys" in the anonymous hash style constructor are only treated as literals, they can't be expressions themselves. But when you use the array-like referencing, you can use any valid javascript expression to calculate the "key".

Rob Van Dam
yes i considered this approach. however i was hoping to have the names and values in separate objects both initially declared and then called upon later.
Jabes88
sorry im taking a second look at this and this is what i need. thanks :)
Jabes88
+1  A: 

I don't necessarily know how to do it exactly how you want it there. You could however send the object and json_decode() it on the php side.

JS:

$.post("php/dosomething.php",{pNames:pNames, pValues:pVals});

PHP:

$p_names = json_decode($_POST['pNames']);
$p_vals = json_decode($_POST['pValues']);

for($i=0;$i<count($p_names);$i++){
   $$p_names[$i] = $p_vals[$i];
}

Should have the same effect that you're looking for.

munch
the error is client side. i think it doesn't like my period. also, it doesn't look like you are using objects for the parameters.
Jabes88
you're right. it's more of a workaround to pass the object to PHP with a non-object parameter. and then you can turn the object into an array with `json_decode`. it would allow you to make the name from the name object a php variable set to the corresponding value from the values object, if that makes sense.
munch
yep, obviously there are many ways to pass parameters, but I was looking for the above answer. thanks for your help.
Jabes88