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 ?

1
  • You'll need to define the array as var item = {}. Commented May 16, 2014 at 12:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Is there a way I can convert the array into a object ?
@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.
i think var item = new Array(); will also work.
@Manwal — No. It won't. Named properties on arrays will not be serialized.
Thanks man it really gave me a headache. The internet is full of missleading information including stackoverflow.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.