0

Trying to pass an array to a php page using an ajax request. The current response is ction Array() { [native code] } as opposed to the actual array contents (which im positive is not empty). Here my code:

    function GetPaginationPage(array1) {
    var jsonString = JSON.stringify(array1);

    $.ajax({
        type: "POST",
        url: "includes/get_pagination_page.php",
        data: {data : jsonString},
        success: function(data){ 
        $('.contestants_list').append(data);
        }
        });
};

UPDated with json, its now passing 'undefined'

Jonah Katz
  • 5,230
  • 16
  • 67
  • 90
  • 1
    possible duplicate of [Send array with Ajax to PHP script](http://stackoverflow.com/questions/9001526/send-array-with-ajax-to-php-script) – Felix Kling Jul 12 '12 at 15:16
  • use an Object instead, everything is preatty much the same. Like data = new Object() ... data['some_key'] = 'some_value'; ... and you can send it over just fine. – Carlo Moretti Jul 12 '12 at 15:17
  • How are you calling `GetPaginationPage`? What happens when you `console.log(array1)`? – gen_Eric Jul 12 '12 at 15:27
  • Using a php array.`GetPaginationPage();` $contestants_array being an array – Jonah Katz Jul 12 '12 at 15:29
  • @JonahKatz: You can't pass PHP arrays to JavaScript like that. Use `GetPaginationPage();` – gen_Eric Jul 12 '12 at 15:30

3 Answers3

1

There's no reason to use JSON.stringify here. Just send the array normally to PHP.

function GetPaginationPage(array1) {
    $.ajax({
        type: "POST",
        url: "includes/get_pagination_page.php",
        data: {
            data: array1
        },
        success: function (data) {
            $('.contestants_list').append(data);
        }
    });
}

Now in PHP, $_POST['data'] will be an array.

UPDATE: You said you're calling GetPaginationPage like this:

GetPaginationPage(<?php echo $contestants_array; ?>);

You need to change that to:

GetPaginationPage(<?php echo json_encode($contestants_array); ?>);

When you echo an array in PHP, it gets converted to the string "Array", which is intrepreted by JavaScript as the Array object.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • think were getting close. Its now posting `data:[object Object] data:[object Object] data:[object Object]` where we need the actual object, not the face that its an object – Jonah Katz Jul 12 '12 at 15:35
  • @JonahKatz: Seems like it's being converted to a string somewhere. Make sure you're not using `.join(',')`, that won't work with an array of objects. What happens when you `console.log(array1)`? – gen_Eric Jul 12 '12 at 15:42
0

Convert the array to a string before passing it like so:

array1.join(',');

Or if it's a complex array consider JSON:

JSON.stringify(array1);
Tom Walters
  • 15,366
  • 7
  • 57
  • 74
0

The way I did this was to create the array in JavaScript as a delimited (~) string & then I used the explode php function to load into an array.

Nigel B
  • 3,577
  • 3
  • 34
  • 52