1

I have an html form, a button and a click handler to manage the submission of the form. Question is specifically about the handler of the button to submit the form via AJAX.

This is the handler I wrote:

JS:

            $('#create').click(function(event) {
                console.log('Create Button Click');
                var dataJSON = JSON.stringify( $('#customer_form').serializeArray() );
                console.log(dataJSON);
                $.ajax({
                    type: "POST",
                    url: "/customer/",
                    // The key needs to match your method's input parameter (case-sensitive).
                    data: dataJSON,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(data){
                        console.log('Success');
                        console.log(data);
                    },
                    failure: function(errMsg) {
                        console.log('Error');
                        console.log(errMsg);
                    }
                });
                event.preventDefault();
            });

I have used JSON.stringify( $('#customer_form').serializeArray() ); to generate the JSON string, getting as result -as shown by console.log(dataJSON):

[{"name":"name","value":"n"},{"name":"address_line_1","value":"a1"},{"name":"address_line_2","value":"a2"},{"name":"town","value":"t"},{"name":"postal_code","value":"p"},{"name":"region","value":"r"},{"name":"phone_1","value":"p"},{"name":"phone_2","value":"pa"},{"name":"fax","value":"f"},{"name":"email","value":"e"},{"name":"web","value":"w"}]

Which would be the easiest way to get the following structure:

[{"name": "n", "address_line_1": "a1", "address_line_2": "a2", "town": "t", "postal_code": "p", "region": "r", "phone_1": "p", "phone_2": "pa", "fax": "f", "email":"e", "web": "w"}]
M.E.
  • 4,955
  • 4
  • 49
  • 128
  • if you really want that I suspect you have to write it yourself. But can you not submit this as normal form data? In which case you can just use `data: $('#customer_form').serialize()` and it should send something equivalent. Depends what your server accepts, but lots of frameworks accept either JSON or serialised form data. – ADyson Jan 08 '18 at 15:35
  • @cale_b serialise() doesn't produce JSON, it produces a querystring, which can't easily be converted into JSON either. Not equivalent. See my comment above though because it's possible the server might accept that anyway. – ADyson Jan 08 '18 at 15:36
  • My backend is a custom web service in Python -nameko framework-. I would like to process stuff in JSON as service might well receive requests from another processes. But information about serialize and that a JSON can't be "directly" be generated from the front-end in JS is quite useful – M.E. Jan 08 '18 at 18:59
  • well, to be pedantic, it _can_ be generated automatically, it's just not in the structure you wanted, that's all. And of course, it's possible to write your own routine to produce the output you'd prefer. – ADyson Jan 09 '18 at 10:11

2 Answers2

2

Something like this should work.

let obj = {}
for (let object in array) {
    obj[object['name']] = object['value']
} 
Nikola Andreev
  • 624
  • 4
  • 18
  • 2
    Code-only answers aren't as useful, can you add an explanation / comments in the code to explain what you are doing? – random_user_name Jan 08 '18 at 15:38
  • Also worth mentioning that `let` is ES6 only, and may want / need to use `var` for compatibility with IE10 and some other browsers. – random_user_name Jan 08 '18 at 15:39
  • 1
    @cale_b I don't think is necessary to explain obvious things like let usage. – Nikola Andreev Jan 08 '18 at 15:42
  • I was totally unaware about `let` and `var` differences. I thought in JS `var` defined a variable. I guess I shall use `let` in this context as the variable is intented to be used only within that context/block. – M.E. Jan 08 '18 at 18:39
  • Here you can see everything explained in details. https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable – Nikola Andreev Jan 08 '18 at 18:48
  • @M.E. "I thought in JS var defined a variable" It does. And it scopes it. It's fine for most cases. There's a subtle difference between let an var, best explained here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let . The other issue as pointed out by cale_b is that some slightly older browsers don't understand it, as it's a fairly new keyword. So whether you use it depends on what browser environments you're required to support. There's a compatibility chart at the bottom of that documentation link. – ADyson Jan 09 '18 at 10:15
0

var arr = [{"name":"name","value":"n"},{"name":"address_line_1","value":"a1"},{"name":"address_line_2","value":"a2"},
{"name":"town","value":"t"},{"name":"postal_code","value":"p"},{"name":"region","value":"r"},{"name":"phone_1","value":"p"},{"name":"phone_2","value":"pa"},{"name":"fax","value":"f"},{"name":"email","value":"e"},{"name":"web","value":"w"}];

var acc = {};
//firstly lets flat your name and value to one new object
var newArr = arr.map(item=>{
                  var newItem={};
                  newItem[item.name] = item.value;
                  return newItem;
                });
     
//secondly we reduce flat all rows inside the newArr..
//..to one unique object acc   
newArr.forEach(item=>{
    Object.keys(item).forEach(key=> acc[key] = item[key]); 
});
 
//now you one unique object which you can serve..
// inside a new array [acc]
console.log([acc])