Today, I'm working the first time with Ajax and facing a strange problem. While using jQuery to make an Ajax 'POST' request, it creates some strange syntax. I haven't found an answer to this in other questions, actually, I also don't know what I should look for.
With Postman I used this as the body of my 'POST' Request:
{
"name": "t.bchuaer@test.de",
"automaticDelete": false,
"cc": {
"ccFolder": false,
"smartDelete": false,
"deletionDays": 182
},
"filters": [
{
"id": 0,
"active": false
}
]
}
When I use GET
to get the objects (without Ajax) it returns exactly this. However, when I use POST
with Ajax and get it through the same GET
method as the other objects, I receive this:
{
"name": "test@tester.com",
"automaticDelete": "false",
"cc[ccFolder]": "false",
"cc[smartDelete]": "false",
"cc[deletionDays]": "182",
"id": 4
}
My jQuery code looks like this:
var emailAccount = {
"name": emailAddress.val(),
"automaticDelete": false,
"cc": {
"ccFolder": false,
"smartDelete": false,
"deletionDays": 182
},
"filters": []
};
$.ajax({
type: 'POST',
url: basicUrl + 'emails',
data: emailAccount,
success: function() {
...
},
error: function() {
...
}
});
What I've tried so far:
- using
dataType: "json"
- using
contentType: 'application/json'
(leads to an 500 error from json-server)
So my question is: What is this?
"cc[ccFolder]": "false",
"cc[smartDelete]": "false",
"cc[deletionDays]": "182"
And why does Ajax create it like this?
I access the code like this:
function getData(path, followUp, id) {
var dataRequest = new XMLHttpRequest();
dataRequest.open('GET', basicUrl + path);
dataRequest.onload = function() {
var receivedData = JSON.parse(dataRequest.responseText)
gotEmails(receivedData)
};
dataRequest.send();
}
function gotEmails(data) {
for (i = 0; i < data.length; i++) {
var userEmailAccount = {
id: data[i].id,
name: data[i].name,
automaticDelete: data[i].automaticDelete,
cc: data[i].cc,
filters: []
};
if (data[i].filters != 'undefined') {
var filterQuery = queryBuilder("filters?", data[i].filters);
getData(filterQuery, 9, data[i].id);
}
}
}