简体   繁体   中英

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

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

You would get:

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

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)

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()

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']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM