2

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.

1 Answer 1

3

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()};
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Adding a parseInt around n['value'] should do the trick: json['iQty'] = parseInt(n['value']);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.