views:

61

answers:

2

I've just tried and more or less given up on sending an array to a jQuery post function, which are then layed out as POST variables.

I've read a lot of the similar questions on here, but none seems to quite get it.

I tried all I could, closes was the following

function sendValue(requestArray, requestAction){
$.post("requests.php", { request: requestAction, 'requestArray[]': function () { $.each(requestArray, function(key, value) { return key: value; }); } }, function(data){    $('#display').html(data.returnFromValue);

 }, "json");
}

wrong tree, barking? I have since got this to work by serializing the what was the requestArray and passing to PHP to be parse_str, but any guideance might well help get this the way I wanted.

A: 

Right now it looks like you're passing a function as a request parameter. I'd just pull that code out and assemble your map first, then pass it to the post function.

function sendValue(requestArray, requestAction){
   var requestParameters = {};
   requestParameters["request"] = requestAction;
   $.each(requestArray, function(key, value) {
      requestParameters[key] = value;
   });
   $.post("requests.php", requestParameters, function(data){ $('#display').html(data.returnFromValue); }, "json");
}

If you really want them to stay in a map instead of flattening them out, maybe try something like this. I'm not sure if PHP would handle it automatically, but you could maybe write some PHP code to assemble the map yourself.

function sendValue(requestArray, requestAction){
   var requestParameters = {};
   requestParameters["request"] = requestAction;
   $.each(requestArray, function(key, value) {
      requestParameters["requestArray[" + key + "]"] = value;
   });
   $.post("requests.php", requestParameters, function(data){ $('#display').html(data.returnFromValue); }, "json");
}
Jennifer Grucza
A: 

As far as I know, if you add square brackets to a form input, PHP will expect that key to contain a flat sub-array, so:

<input name="foo[]" value="blahblah"/>
<input name="foo[]" value="blahblah"/>

will yield an array like:

array("foo" => array("blahblah", "blahblah"));

I do not think it is possible to have numerous key/value pairs within your requestArray[], like what you are trying to do, e.g. to get on the server something like:

array("foo" => array("bar" => "baz, "hehe" => "hahah"))

so I think your approach which involves serializing the sub-array on the client and parsing it on the server, in this case, seems to be the correct one.

karim79