Search code examples
javascriptjqueryajaxarraysprototypejs

Javascript Array / jQuery .data()


I've an attached data which contain an ID list used like this :

//Create
$('#element').data('list', new Array());
//Add a value into data
$('#element').data('list').push(id);
//Remove an element
var inArray = jQuery.inArray(id, jQuery('#element').data('list'));
if(inArray != -1) jQuery('#element').data('list').splice(inArray, 1);

I want to send this data to PHP throught an Ajax call using prototype.
It looks like this : [1,2,3] will be replace by jQuery('#filmsList').data('listFilms')

ajax: {
   method: 'post',
   parameters : {'values' : [1,2,3]},
   evalScripts: true,
}

And the posted params are :

values  1
values  2
values  3

So in PHP I retrieve only

array(1) {
  ["values"] => string(1) "3"
}

What am I doing wrong?

And If I don't put my array in the object parameters : [1,2,3], I retrieve a lot of functions attached to my data like this :

array(40) {
[0] => string(6) "1"
[1] => string(6) "2"
[2] => string(6) "3"
["each"] => string(233) "function each(iterator, context) {
  var index = 0;
  try {
    this._each(function(value) {
      iterator.call(context, value, index++);
    });
  } catch (e) {
    if (e != $break) throw e;
 }
  return this;
}"
["eachSlice"] => string(291) "function eachSlice(number, iterator, context) {
 var index = -number, slices = [], array = this.toArray();
  if (number < 1) return array;
  while ((index += number) < array.length)
   slices.push(array.slice(index, index+number));
  return slices.collect(iterator, context);
}"
["all"] =>......

Solution

  • Those functions appearing in your output are from Prototype JS, not from jQuery.

    Something in the functions you're calling to serialise the array is doing so without checking for obj.hasOwnProperty(n).

    However - PHP will be expecting your form parameters to be key: value pairs, not as an array. There's no widely acceptable standard for passing multiple values for a single key, so a portable approach might be to manually serialise the array first, e.g.:

    parameters: { 'values': JSON.stringify(myArray) }
    

    and then perform JSON decoding of $_REQUEST['values'] in the PHP code.

    If you know it's only every going to be PHP you can use:

    parameters: { $.param({ 'values[]': myArray }) }
    

    which relies on jQuery to convert the values[] key into a format that PHP is known to be compatible with.