15

I'm using jQuery to post JSON to a Java server, but I think my JSON must be wrong. Here's an example of my data and how I'm sending it:

var lookup = {
    'name': name,
    'description': description,
    'items': [{
        'name': itemName,
        'value': itemValue
    }]
}

$.ajax({
    type: 'post',
    data: lookup,
    dataType: 'json'
});

I'm using Wicket's AbstractAjaxBehavior to receive the data and would like to get a single JSON string that I can parse. When I get a Map of the parameters passed, the keyset looks like this:

items[0][name],
description,
name,
items[0][value],

Obviously I can easily get the values for name and description, but the key for my array of items is messed up. I'm sure it's something simple, but I seem to keep running around the solution. Any suggestions? Thanks!

Jared
  • 1,254
  • 7
  • 19
  • 26
  • Hi Could you post your Wicket AjaxBehavior code. I has a problem (http://stackoverflow.com/questions/4976244/using-wicket-abstractajaxbehavior-with-jquery-ajax ) in that my onRequest() does not seem to be receiving any data. Thanks – user193116 Feb 12 '11 at 14:48

1 Answers1

47

You have to use JSON.stringify:

$.ajax({
    type: 'post',
    data: JSON.stringify(lookup),
    contentType: 'application/json',
    dataType: 'json'
});

You should also specify 'application/json' as the contentType. By default jQuery will serialize objects with application/x-www-form-urlencoded (even if the contentType is application/json'). So you have to do it manually.

EDIT: Key for 'post' should be type, not method.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • 1
    jQuery automatically adds the content type as application/json when you specify the dataType as json, doesn't it? I did need to stringify my JSON, though, which solved my problem. Thanks for catching that! Also, if you want your data to come back as a parameter value and not a key, send it like this: `data: {'lookup': JSON.stringify(lookup)}` – Jared Jul 06 '10 at 13:39
  • 5
    @Jared, no. `dataType` specifies what you expect the server to send. `contentType` is the content type *you're* sending, and jQuery will not change it based on dataType. And `{'lookup': JSON.stringify(lookup)}` isn't quite correct. If lookup is `{foo: "bar"}`, that will be url-encoded to something like `lookup=%7B%22foo%22%3A%22bar%22%7D` That obviously isn't a valid JSON document. When you're posting application/json, you don't use url-encoding. I think this might be connected to you putting `method: 'post'`. It should be type: 'post'. Method is ignored, and the default is GET. – Matthew Flaschen Jul 07 '10 at 00:55
  • 2
    Note: If you get a "JSON is undefined" error (IE6/7) you'll need to include json.org's latest json.js file in your page. – Jared Jul 12 '10 at 17:54