0

I'm having this problem, where basically, I have a big array, that I break down to smaller arrays each time the loop does a loop. Within the loop I have an ajax call which sends that array to a url. The problem is that it only makes the ajax call once, but it logs the other smaller arrays in the console. Any idea why this is happening?

  //emailArray = [email1@something.com, email2@something.com..... (up to a number greater than 10)
  while(emailArray.length) {
            console.log(emailArray.splice(0,10));



            $.ajax({
                url:"some/url",
                type: "POST",
                data: {
                    "object": emailArray.splice(0,10)
                },
                dataType: "json",
                success: function (data, status, xhr) {
                    //callback(data);
                    console.log('data from success');
                    console.log(data);
                }
            });
            console.log('after ajax');
        }

Edit, the loop is designed to send a new ajax request for every 10 items in the big array, and the array that is sent has 10 items in it. The .splice breaks up the arrays fine when I just log them in the console... but it's not doing the ajax part

Bill
  • 5,478
  • 17
  • 62
  • 95

1 Answers1

3

.splice() is destructive on the source array so your console.log(emailArray.splice(0,10)); is messing up emailArray and causing you to miss iterations.

You can use .slice() (which is not destructive, but returns a copy) instead of .splice() in the console.log() statement like this:

  //emailArray = [email1@something.com, email2@something.com..... (up to a number greater than 10)
  while(emailArray.length) {
            console.log(emailArray.slice(0,10));

            $.ajax({
                url:"some/url",
                type: "POST",
                data: {
                    "object": emailArray.splice(0,10)
                },
                dataType: "json",
                success: function (data, status, xhr) {
                    //callback(data);
                    console.log('data from success');
                    console.log(data);
                }
            });
            console.log('after ajax');
        }
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • That worked! Thanks... haha the fact that I was trying to debug it was breaking it the whole time :) – Bill Sep 01 '11 at 18:29
  • That's one reason why `splice()` is a somewhat tricky array function and is why I didn't use it in my other answer to you here: http://stackoverflow.com/questions/7273668/split-a-long-array-into-smaller-arrays-with-jquery/7273765#7273765. You have to be aware that it is modifying the source array when using it. – jfriend00 Sep 01 '11 at 18:32