Scriptomaniac Scriptomaniac - 2 years ago 58
Javascript Question

JSON isn't posting correctly

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
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){

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
, 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",

Answer Source

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){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download