Question

I get data is undefined, i guess i can't ['productId'] in an array, but i think i need this structure in the json, i tried a couple of variation but it never was, what i needed i just want to send a json via ajax.

jQuery(':checked').each(function(i){
  data[i]['productId'] =  jQuery(this).parent().find('.productId').val();
  jQuery(this).parent().find('.attrGrp').each(function(j){
    data[i]['attrGrps'][j]['uid'] = jQuery(this).find('.active').attr('id');
    data[i]['attrGrps'][j]['amount'] = jQuery(this).parent().find('.amount').val();
  });
});
jQuery.post(newSession, {json: data.serializeArray()});

is there any better way for doing it? or how can i make it work? help appreciated ;/

Was it helpful?

Solution

You need to initialize arrays and objects before using them. String indexes are only possible with objects. Try this:

var data = [];
jQuery(':checked').each(function(i)
{
  data[i] = {};
  data[i].productId =  jQuery(this).parent().find('.productId').val();
  data[i].attrGrps = [];
  jQuery(this).parent().find('.attrGrp').each(function(j)
  {
    data[i].attrGrps[j] = {};
    data[i].attrGrps[j].uid = jQuery(this).find('.active').attr('id');
    data[i].attrGrps[j].amount = jQuery(this).parent().find('.amount').val();
  });
});

Alternatively you could use jQuery().serialize, post everything in the form and sort it out on the server.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top