superphonic
superphonic

Reputation: 8074

Unable to post Javascript array via jQuery ajax

I am extremely reluctant to ask this question as I know it is something really stupid I am missing, but I simply cannot get this to work. Code below:

<script>

var formArray = new Array();
formArray['start'] = "one";
formArray['stopat'] = "two";
formArray['stop_at'] = "three";

$('#my_button').click(function() {
    $.ajax({
        type: "POST",
        url: "scheduler.php",
        data: formArray,
        success: function(response){

            console.log(response);

        }
    });
});
</script>

Server side PHP Script scheduler.php

<?php

    print_r($_POST);

?>

All I get back logged to the console is an empty array:

Array
(
)

If I console.log formArray within the click function it shows the complete array just fine. So why is it not posting it to my PHP file?

Thanks in advance

Upvotes: 2

Views: 508

Answers (4)

Prateek
Prateek

Reputation: 6975

JavaScript Arrays are designed to hold an ordered sequence of items with integer keys. When jQuery converts a data structure into Form URL Encoded data and encounters an array, it will iterate over those integer keys and not over named keys.

Use an Object if you want to have named keys.

Change new Array() to newObject()

Upvotes: 1

user229044
user229044

Reputation: 239581

You are adding string properties to an array, which is for storing numeric indices.

Use an object instead:

var formArray = {};
formArray['start'] = "one";
formArray['stopat'] = "two";
formArray['stop_at'] = "three";

jQuery will iterate over the indices in an array, using a for (var i = 0; i < formArray.length; ++i) loop, which will completely miss any properties you've added to the array.

Also, new Array should have been [] (as {} should be preferred over new Object). Don't use the new X method of initialization for built-in types. (Crockford, The Good Parts)

Upvotes: 2

Vince
Vince

Reputation: 1851

Changing Array() to Object() would work as well.

You would get:

Array
(
    [start] => one
    [stopat] => two
    [stop_at] => three
)

Upvotes: 3

sravis
sravis

Reputation: 3680

Edit your Ajax like this and see if it works: data: {data: formArray}, dataType: 'JSON'

$.ajax({
        type: "POST",
        url: "scheduler.php",
        data: {data : formArray},
        dataType: 'JSON'
        success: function(response){

            console.log(response);

        }
    });

PHP:

print_r($_POST['data']);

Upvotes: 0

Related Questions