Jack
Jack

Reputation: 513

Why does ajax `data` cause this code to break?

I'm new to JavaScript but I've written some code that as far as I can see is formatted correctly however when I add the data elements in it breaks the code but I cannot see why as according to the jQuery documentation, I am using .val() correctly etc.

<script>
$( "#button1" ).click(function() {
    $('#table').DataTable( {
        "ajax": {
                "data": [
                    "date1": $( "#inputDate1" ).val(),
                    "date2": $( "#inputDate2" ).val(),
                ],
                "url": "/server_processing/database.php",
                "type": "POST"
                },
        "serverSide": true
    } );
} );
</script>

Upvotes: 2

Views: 66

Answers (2)

Lund
Lund

Reputation: 272

You had one comma that does not belong there. As stated below, another problem is that arrays cannot have associative keys .

<script>
$( "#button1" ).click(function() {
    $('#table').DataTable( {
        "ajax": {
                "data": {
                    "date1": $( "#inputDate1" ).val(),
                    "date2": $( "#inputDate2" ).val() // No , here
                },
                "url": "/server_processing/database.php",
                "type": "POST"
                },
        "serverSide": true
    } );
} );
</script>

Upvotes: 2

Quentin
Quentin

Reputation: 944204

An array literal [] contains a comma separated list of items.

An object literal {} contains a comma separated list of key : value pairs.

You have the body of an object literal inside an array literal.


Having a trailing comma in array or object literals, while valid in some versions of JS, can be problematic. So remove that too.


            "data": {
                "date1": $( "#inputDate1" ).val(),
                "date2": $( "#inputDate2" ).val()
            },

Upvotes: 3

Related Questions