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.
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.
1 Answer
Reset to default 17I'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>
data: JSON.stringify(data)
– Alessandro Commented May 16, 2017 at 13:43