1

I have a custom page builder for a client, where-by they can build out their own web forms via a drag and drop back-end.

At the moment, I can get the data to output in a JSON format such as the following:

{ 
  "email":"[email protected]",
  "geoip_country":"XXYY",
  "geoip_state":"XXYY",
  "geoip_city":"XXYY",
}

But, I need to alter the output in the following format, I'd like to seperate out the email field from the form, and drop all other data nested inside the dynamic_attributes section, like this:

{
    "email":"[email protected]",
    "dynamic_attributes":{
        "geoip_country":"XXYY",
        "geoip_state":"XXYY",
        "geoip_city":"XXYY",
        // all other form fields here.

    },
}

Could anyone point me in the right direction? I'm not hugely experienced with outputting JSON - I should also add that the json is being created from the following jQuery function:

(function ($) {
    $.fn.serializeFormJSON = function () {

        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
})(jQuery);

See Fiddle: https://jsfiddle.net/fish_r/m46zLdo9/3/

Thanks!

3
  • Is dynamic_attributes a constant property name? If not where would that property name come from? How are fields separated as primary or children? Show some sample html Commented Nov 13, 2017 at 0:30
  • Both dynamic attributes and and the email are constant property names, the data nested within the dynamic attributes is what would be dynamically generated. Edited to add fiddle link Commented Nov 13, 2017 at 0:35
  • So it is a simple form and always has one primary field being email and all others are nested? I suspect there is a higher level of complexity than that no? Commented Nov 13, 2017 at 0:40

2 Answers 2

1

Try this :

$('#myform').submit(function(e) {
    e.preventDefault();
    var data = $(this).serializeFormJSON();
    console.log(data);
});

(function ($) {
    $.fn.serializeFormJSON = function () {
		
        var o = {};
        var dynamic_attributes = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (this.name =='email') {
              if (o[this.name]) {
                  if (!o[this.name].push) {
                      o[this.name] = [o[this.name]];
                  }
                  o[this.name].push(this.value || '');
              } else {
                  o[this.name] = this.value || '';
              }
            } else {
              if (dynamic_attributes[this.name]) {
                  if (!dynamic_attributes[this.name].push) {
                      dynamic_attributes[this.name] = [dynamic_attributes[this.name]];
                  }
                  dynamic_attributes[this.name].push(this.value || '');
              } else {
                  dynamic_attributes[this.name] = this.value || '';
              }   
            }
        });
        o['dynamic_attributes'] = dynamic_attributes;
        
        return o;
    };
})(jQuery);
.hidden {opacity:.3}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="POST" id="myform">
  <input type="text" name="name" placeholder="name"><br/>
  <input type="email" name="email" placeholder="Enter your email"><br/>
  <input type="text" name="address1" placeholder="Enter the first line of your address"><br/>
  <input type="submit">
</form>
<div id="output"></div>

Sign up to request clarification or add additional context in comments.

3 Comments

Amazing, Thank you - I've gained a good understanding of how we've created these from our vars at the top, I've gone ahead and created another property named extra_parameters, as we also need that for our integration. - One further question, do you know how I could possible exclude certain inputs by name/class or ID from being included?
Ignore that, I've managed to get this working by cloning the form in jquery, removing the hidden inputs and then running the serializeFormJSON() function. Thanks again Sunwoo.
I apologize for confirming the comments later. Glad to hear that.
0

To anyone looking for help on a similar issue in the future, I've created a library to allow forms to be sent as deep nested JSON objects by writing the name attributes of each input as a series of subkeys joined by "." characters.

To import the library:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/deepforms.min.js"></script>

An example form made using the library:

<form id = "exampleForm" method = "POST" action = "/submitForm">
    <input type = "text" name = "user.name" value = "testUser">
    <input type = "text" name = "color" value = "blue">
    <input type = "text" name = "color" value = "red">
</form>
<button onclick="document.deepforms.submitDeepForm('exampleForm')">

Upon clicking the submit button, the following object will be generated and sent as a JSON string:

{
    "user" : {
        "name" : "testUser"
    },
    "color" : ["blue", "red"]
}

The JSON string is sent as the value of a parameter called deepFormJSON:

deepFormJSON : '{"user":{"name":"testUser"},"color":["blue","red"]}}'

Which can be parsed as a JSON string in order to construct an object at the request destination.

Comments

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.