I'm trying to post some data to a http connector but cant figure out how i can post Array data...
My data Looks like that:
var data = [{
key:'myKey',
keyName:'myKeyName',
value:'value',
valueName:'valueName'
}, {
key:'mySecondKey',
keyName:'mySecondKeyName',
value:'secondValue',
valueName:'secondValueName'
}, ...and so on ];
I try to post it via Ajax like this:
$.ajax({
type: "POST",
url: url,
data: data,
error: function(){
alert("Error");
},
success: function(){
alert("OK");
}
});
The request Returns ok but when i look at the request data it Posts undefined=value&undefined=secondValue
How can i solve this? I Need to save all those informations for configurations
A simple post with just some keys and values like key=value&key2=value2
works like a charm.
To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type. Given below is the method prototype: void method_name (int [] array);
In JavaScript, the array is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable.
Note – You can pass JavaScript Array variable as same as any other variable in AJAX request.
DataTables has the ability to read data from virtually any JSON data source that can be obtained by Ajax. This can be done, in its most simple form, by setting the ajax option to the address of the JSON data source.
I'm assuming you're making a POST request with a JSON payload. First, you want to make sure your payload is formatted JSON correctly, use: http://pro.jsonlint.com/
Secondly, you can send the payload using JSON.stringify and you will want to set the contentType:
data: JSON.stringify(data), contentType: "application/json; charset=utf-8"
If you run this and look at your network tab in Dev Tools in Chrome, it will error out, but you will at least see the payload formatted to send to the server: http://prntscr.com/f8hf6s
var data = [{
"key": "myKey",
"keyName": "myKeyName",
"value": "value",
"valueName": "valueName"
},
{
"key": "mySecondKey",
"keyName": "mySecondKeyName",
"value": "secondValue",
"valueName": "secondValueName"
}
];
var url = "http://swapi.co/api/";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function() {
alert("Error");
},
success: function() {
alert("OK");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With