0

I now this question has been asked before but I am trying to work this out since this morning and I can't get it right.

I have a global variable named items

I have a .ajax request that I need to send the contents of the items array

Items is like this

items = new Array();

for (var i = 0; i < 10; i++)
{
   //just populating the list
   var item = [];

   item['some_stuff'] = 'string';
   item['some_int'] = 373;

   items.push(item);

}

//here is the request

    if (items.length > 0)
    {   
        $.ajax({
                type : "POST",
                url  : "/grad1/adaugaComanda.php",
                data : { "stuff" : items},
                success : function (data){

                    alert(data);
                //  window.location = '/dashboard.php?categ=5&sel=1';

                }
                });
    }

//

The request is executed but data is not sent. I tried to use JSON.stringify on the array but it returns empty ([[]]).

Any ideas what I am doing wrong ?

opc0de
  • 11,557
  • 14
  • 94
  • 187

1 Answers1

3
   //just populating the list
   var item;

This declares a variable called item but does not give it a value to it so it is undefined

   item['some_stuff'] = 'string';

This attempts to assign a value to the some_stuff property of undefined. This isn't allowed, so JS will throw an exception and script execution will cease.

You aren't making a request at all, because your script isn't getting far enough to do that.

You need to assign an object to item:

var item = {}

You have edited your question so your code now reads:

var item = [];

You still need to use a plain object here ({} not []). Array objects should only have numeric indexes. jQuery will ignore named properties on an array when serializing it.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Is there a way I can convert the array into a object ? – opc0de May 16 '14 at 12:53
  • @ring0 — *possibly*, but I'm not certain and all the potential approaches I can think of are horrible. You really should use an object in the first place. An array is simply the wrong data structure to use in the first place. – Quentin May 16 '14 at 12:54
  • i think `var item = new Array();` will also work. – Manwal May 16 '14 at 12:55
  • @Manwal — No. It **won't**. Named properties on arrays will **not** be serialized. – Quentin May 16 '14 at 12:55
  • Thanks man it really gave me a headache. The internet is full of missleading information including stackoverflow. – opc0de May 16 '14 at 12:58
  • Horrible hack — `var foo = []; foo.bar = "testing"; var bar = {}; for (var p in foo) { bar[p] = foo[p] };` will create an object with the same properties as an array, you might still trip over the prototype chain, I had no luck in converting an array to an object — you should still use an object in the first place for named keys. – Quentin May 16 '14 at 13:01