Reputation: 232
So I'm trying to add an object with a bunch of attributes inside of it.
This is the object I'm trying to $.post
({"fname" : fname,
"lname" : lname,
"gender" : gender,
"traits" : {
"iq" : intellect,
"height" : height,
"speed" : speed,
"weight" : weight,
"stamina" : stamina,
"toughness" : toughness
},
"homeState" : homeState,
"country" : country
});
Prior to posting the object, everything works fine. I can do obj.traits.iq
and it will return the exact iq needed, etc. looking at the inspector, "traits" comes up as an Object.
The problem starts once I post it with this function
$.post( url, obj, function(data){
console.log(data);})
}
The object gets posted and I can access it, but it's formatting is all weird.
Instead of traits showing as "traits": Object;
it shows as traits[iq]: 100, traits[height]: 5'6
,, etc. Rather than showing up as an acccessible object, it just automatically shows all traits in that format. What am I doing wrong? I don't even know what to look up, or why it's happening.
The problem this causes is that there are other objects in the API that return correctly, where their "traits" shows up as "traits":object
, rather than traits[iq]: 100 traits[height]: 5'6
, etc. This causes all of the functionality I have written around the API to not work on any new object that I add.
API Info:
Example request
POST /apikey/players HTTP/1.1
Accept: application/json
Content-Type: application/json
Host: --------
{
"fname": "Steve",
"lname": "Harley",
...
}
Example Response: the post is supposed to return the object with a new id property
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Date: Fri, 10 SEPT 2014 12:24:28 GMT
{
"id": 11,
"fname": "Steve",
"lname": "Harley",
...
}
Upvotes: 1
Views: 66
Reputation: 45
Some API can send us the response in diferent formats depending on which format we have specified at the request (this type of API can be easily done with ASP.NET for example). Have you tried to explicit specify the dataType parameter as json, like this?
$.post(url, obj, function(data) {
console.log(data);
}, "json");
Upvotes: 0
Reputation: 97672
It looks like the api expects json, which is not what you're sending.
To send json you have to encode the data to json and se
$.post( {
url: url,
data: JSON.stringify(obj),
contentType: 'application/json',
success: function(data){
console.log(data);
}
});
Upvotes: 1