0

I need to pass array of ids with $.ajax data variable. The array is a result of a function. If i declare this function outside $.ajax it sends array correctly. But if i put same function code inside $.ajax (which is preffered for me), i get it as a string.

function mySort(){ // Do not pass hidden clones
    var items = [];
    $('#fp_parameters_list').children().each(function(){
        if ($(this).is(':visible')) {         
            items.push($(this).attr('data-parameter-id'));
        }
    });
    return items;
}

// This gives correct ordering
$.ajax({
    url: '/echo/json/',
    type: 'post',
    dataType: 'json',
    data: {
        ordering: mySort()
    }
});


// This gives ordering as a string
$.ajax({
    url: '/echo/json/',
    type: 'post',
    dataType: 'json',
    data: {
        ordering: function(){ // Do not pass hidden clones
            var items = [];
            $('#fp_parameters_list').children().each(function(){
                if ($(this).is(':visible')) {         
                    items.push($(this).attr('data-parameter-id'));
                }
            });
            return items;
        }
    }
});

Here's fiddle: http://jsfiddle.net/vxLrN/7/

You can see that first request is sent with ordering as an array, while second pass ordering as string, although, functions are absolutely equal.

How can i put function inline and still get array result? Thanks

Alex
  • 731
  • 1
  • 7
  • 8

2 Answers2

4

Well make sure that you invoke this anonymous function in order to assign the proper result (array of strings) to the ordering parameter:

data: {
    ordering: (function () { // Do not pass hidden clones
        var items = [];
        $('#fp_parameters_list').children().each(function() {
            if ($(this).is(':visible')) {
                 items.push($(this).attr('data-parameter-id'));
             }
         });
         return items;
    })(); // <!-- Here call the anonymous function to get its result
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

Just use $.map to build the array directly instead

$.ajax({
  url: '/echo/json/',
  type: 'post',
  dataType: 'json',
  data: {
    ordering: $.map($('#fp_parameters_list').children(':visible'), function(el) {
                 return $(el).data('parameter-id');
              })
  }
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • This is even less code. Although, i accepted Darin's reply as it was more close to the topic, but i guess i will use your solution. Thanks – Alex Mar 29 '14 at 10:06