notAnonymousAnymore
notAnonymousAnymore

Reputation: 2687

Generating a dynamic JSON object

(I hope I can explain this problem properly... have a feeling I might be crucified...)

I have a dynamically generated HTML form filled with select lists which then get saved to the db using AJAX.

The select lists are named like this:

<select id="slFieldName1"><option value="A">A</option><option value="B">B</option></select>

<select id="slFieldName2"><option value="A">A</option><option value="B">B</option></select>

etc.

FieldName1, FieldName2, etc, are the actual column names on the database table - I am using reflection to get and set values.

Here is the process:

Client side:

$('#btnSave').click(function (e) {
    var sData = {
        FieldName1: $('#slFieldName1').val(),
        FieldName2: $('#slFieldName2').val()
    };

    ProjectName.AJAXService.Save(JSON.stringify(sData), function (result) {
        // etc
    });
});

Server side:

public class SurveyData
{
    public string FieldName1 { get; set; }
    public string FieldName1 { get; set; }
}

[WebMethod(true)]
public bool SaveCSSurvey(string sDataJson)
{
    SurveyData sData = JsonConvert.DeserializeObject<SurveyData>(sDataJson);

    List<string> fieldNames = new List<string>(); // this will be populated with the field names

    foreach (var fieldName in fieldNames)
    {
        s.GetType().GetProperty(fieldName).SetValue(s,
            ((string)sData.GetType().GetProperty(fieldName).GetValue(sData)));
    }
}

My question:

How do I dynamically generate the JSON object that I want to pass to the AJAX service? Ie. instead of this:

var sData = {
    FieldName1: $('#slFieldName1').val(),
    FieldName2: $('#slFieldName2').val()
};

...I need to have some kind of JavaScript collection with all the field names, and have this object created by iterating the field names.

Edit: crux of the issue is creating this JSON object. Even if I just iterate through each select list using jQuery, and then get the field name by pruning its 'id' attribute, how would I then create the JSON object.

Upvotes: 2

Views: 80

Answers (3)

charlietfl
charlietfl

Reputation: 171689

If all you are wanting to do is submit the form you can submit it as form encoded data and use serialize(). Assumes using proper name attribute as required by forms.

$.post(url, $('#formId').serialize(), function(resp){
    // do something with response
});

If you really need that object as shown you can loop over each input and map it's name to object

var formData ={};

$('#formId :input').each(function(){
   formData[this.name] = this.value;
});

Upvotes: 1

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

If you want to automatically generate JSON Object from fields. I think the following example is what you looking for.

Output :

Object {FieldName1: "A", FieldName2: "A"}

Hope this helps.


Snippet

$('#btnSave').click(function (e) {
    var sData = {};
  
    $('select[id^="slFieldName"]').each(function(){
         var attribute_name = $(this).attr('id').replace('sl',''); //Removing string 'sl'
         sData [attribute_name] = $(this).val();
    });
  
    console.log(sData); //Object {FieldName1: "A", FieldName2: "A"}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="slFieldName1"><option value="A">A</option><option value="B">B</option></select>
<select id="slFieldName2"><option value="A">A</option><option value="B">B</option></select>

<button id='btnSave'>Save</button>

Upvotes: 0

Peter Aron Zentai
Peter Aron Zentai

Reputation: 11740

In ES5 you can only do this with simple assignment for example in an iteration (versus as an assignment as part of the literal)

var sData = {}
fieldNames = ["FieldName1","FieldName2"]
fieldNames.forEach(function(fieldName) {
  sData[fieldName] = $('#sl'+fieldName).val()
})

In ES6 you could use a more concise way, but this does not support an iteration - just positively setting all field names/values

var sData =  {
   [fieldName] = ...

}

Upvotes: 0

Related Questions