I have a form I'd like to submit as JSON via jQuery AJAX, so that I can read it into a temporary table on the server-side using one my programming language's native methods (OpenEdge using READ-JSON). An example of the JSON my form needs to produce is:

{"ttOrder": [
  {
    "cProduct": "prod01",
    "iQty": 123
  },
  {
    "cProduct": "prod02",
    "iQty": 456
  }
]}

My form is made up of a table containing rows of product information, product code, description etc. and a quantity input field, e.g.

<input id="prod01" name="prod01" value="0">

From searching around Stack Overflow I found a couple of suggestions that looked like they might help, as I think I need to serialise the form:

(function( $ ){
    $.fn.serializeJSON=function() {
        var json = {};
        jQuery.map($(this).serializeArray(), function(n, i){
            json[n['name']] = n['value'];
        });
        return json;
    };
})( jQuery );

var obj = {"ttOrder": [$('#prodform').serializeJSON() ]};

And then in the $.ajax call use

...
data: JSON.stringify(obj),
...

However, this gives the following:

{"ttOrder": [
  {
    "prod01": "123",
    "prod02": "456"
  }
]}

I think that all the code above is doing is creating a JSON string comprising of the input name and value as a key & value pair, but I don't have the know-how to change the code to get me what I require.

I think that what I'm trying to achieve is to have an array of objects where the name of the array is always ttOrder (maps to my temp-table name), the first entry of an object is the product code (always cProduct - maps to my temp-table field name) with a value of the input's name, and the second entry of an object is the quantity (always iQty - maps to my temp-table field value).

Please excuse any incorrect terminology I use.

Thanks.

share|improve this question
up vote 3 down vote accepted

The first example is close. This should work here:

(function( $ ){
$.fn.serializeJSON=function() {
    return jQuery.map($(this).serializeArray(), function(i, n){
        var json = {};
        json['cProduct'] = n['name'];
        json['iQty'] = parseInt(n['value']);

        return json;

    }).get();
};
})( jQuery );

var obj = {"ttOrder": $('#prodform').serializeJSON()};
share|improve this answer
    
Brilliant, and thanks for such a quick solution. It almost works, but the quantity is being turned into a string i.e. {"cProduct": "01", "iQty": "1"} rather than {"cProduct": "01", "iQty": 1}. Is there anything I can do about this? – Ian Stanway Jan 31 '12 at 22:00
    
Adding a parseInt around n['value'] should do the trick: json['iQty'] = parseInt(n['value']); – Brian Geihsler Jan 31 '12 at 23:33
    
Yep that did it, it works perfectly now. Many thanks Brian! – Ian Stanway Feb 1 '12 at 12:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.