简体   繁体   中英

Cannot send array to php via AJAX?

Well I followed this question, but cannot send array to php it returns me always empty:

JS:

            values = [];
            values['mpsRegnomer'] = $('#mpsRegnomer').val();
            values['mpsMarka'] = $('#mpsMarka').val();
            values['mpsMarkaOther'] = $('#mpsMarkaOther').val();
            values['engineType'] = $('#engineType').val();
            values['seatNumberInput'] = $('#seatNumberInput').val();
            values['carColor'] = $('#carColor').val();
            values['mpsChassiNum'] = $('#mpsChassiNum').val();
            values['mpsModel'] = $('#mpsModel').val();
            values['mpsModelOther'] = $('#mpsModelOther').val();
            values['mpsManufactureDate'] = $('#mpsManufactureDate').val();
            values['mpsfor'] = $('#mpsfor').val();
            values['VehicleType'] = $('#VehicleType').val();
            values['dvigatelInput'] = $('#dvigatelInput').val();
            values['engineMaxPower'] = $('#engineMaxPower').val();
            values['is_automatic'] = $('#is_automatic').val();
            console.log(values);

            $.ajax({
                    type: 'POST',
                    url: 'assets/clients/services/saveDataMPS.php',
                    async: false,
                    dataType: "JSON",
                    data: {"values": JSON.stringify(values)},
                    success:function(response){
                        alert(1);
                    }
            });

console.log(values) show me that array is OK.

PHP code:

<?php

var_dump(json_decode($_POST["values"])); exit; 

It returns me always empty, also tried only with var_dump($_POST); same result.. Where am I wrong?

Result from console.log(values) :

在此处输入图片说明

You defined values as an array and therefore when you stringify it, you get an empty array. Define it as an object like values = {}; and it will work.

You don't use associative arrays in javascript because

If you use named indexes, JavaScript will redefine the array to a standard object. After that, some array methods and properties will produce incorrect results.

Thats's why you need to define it as object in the beginning.

values = {};
values['mpsRegnomer'] = $('#mpsRegnomer').val();
values['mpsMarka'] = $('#mpsMarka').val();
values['mpsMarkaOther'] = $('#mpsMarkaOther').val();

Here is a working JSFiddle. http://jsfiddle.net/pk97fe0b/

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