I am trying to send javascript array to php via ajax, but it is not sending, here is my code
var ArrayAmounts = new Array();
ArrayAmounts["P1"] = "16150";
$.ajax({
url:"myajax",
cache:'false',
type:'POST',
data:{Arr:ArrayAmounts},
success: function(data){
console.log(data);
},error: function(xhr, AjaxOptions, ThrownError){
ShowMessage(xhr.responseText);
}
});
but when I am making array like this:
var ArrayAmounts = new Array();
ArrayAmounts[0] = "16150";
it is passing the array, but I want the key as alphanumeric. please help.
So you don't need an array here, you'll need to use an object like this :
var Amounts = {};
Amounts["P1"] = "16150";
$.ajax({
url:"myajax",
cache:'false',
type:'POST',
data:{Arr: Amounts},
success: function(data){
console.log(data);
},error: function(xhr, AjaxOptions, ThrownError){
ShowMessage(xhr.responseText);
}
});
Your problem is related to the kind of data you are sending because as the documentation says:
"It is converted to a query string, if not already a string. It's appended to the url for GET-requests. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting "
you can declare the array like this: var ArrayAmounts = new Array(); ArrayAmounts = ["16150"]; and then your ajax call work normally
Use like this
var ArrayAmounts = {};
ArrayAmounts.P1 = "16150";
var dataArray = {Arr: ArrayAmounts};
$.ajax({
url:"myajax",
cache:'false',
type:'POST',
data: dataArray ,
success: function(data){
console.log(data);
},error: function(xhr, AjaxOptions, ThrownError){
ShowMessage(xhr.responseText);
});
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.