How to concatenate a javascript object to a post form?

1

I have an object JSON that I built at runtime, I need it to be sent to my servlet , along with the other form fields, via post, how do I do this? I researched a lot but nothing worked.

function createJSON() {

    layoutColunas = [];
    $(".colSubWrapper").each(function() {

        var item = {};

        var nomeColuna = $(this).find(".colJSON").eq(0).val();
        item ["nome_coluna"] = nomeColuna;

        var tipoColuna = $(this).find(".colJSON").eq(1).val();
        item ["tipo_coluna"] = tipoColuna;

        layoutColunas.push(item);

    });

    return layoutColunas;
}
$("#formBaseCadastrar").on("submit", function(e){

    e.preventDefault();

    console.log("tentou fazer submit");
    var layoutColunas = createJSON();
    $('.colJSON').prop('disabled', true);
    var data = $("#formBaseCadastrar").serialize();
    data = data + '&' + $.param(layoutColunas);
    console.log(data);
    $.ajax({ 
        url: "/QualidadeWeb/basesCadastrar",
        type: "POST",
        async: false,
        data: data,
        success: function(data){
            console.log(data);
            $("#pageContainer").load("/QualidadeWeb/resultado?resp="+encodeURIComponent(data));
        },  
        error: function(data){
            console.log(data);
            console.log("deu errado");
        }
    });
});

Although my object works normally, this $.param(layoutColunas); function creates a undefined param. When using f12 for tracking the Post Protocol, the result was as follows:

nomeBase=base1234&conexao=234234&telefone=324234&tipoBase=4&undefined=&undefined=

My object is as follows:

Thank you in advance!

    
asked by anonymous 08.02.2018 / 16:51

1 answer

1

According to the function documentation jQuery.param()

  

If the object passed in an Array, it should be an array of objects in the format returned by .serializeArray()

Translating

  

If the last object is in an array , it must be an array of objects in the format returned by .serializeArray()

Sample format required:

[
  { name: "first", value: "Rick" },
  { name: "last", value: "Astley" },
  { name: "job", value: "Rock Star" }
]

jQuery.param() constructs the string parameter using the name and value keys of each object in the array . Your objects only have keys nome_coluna and tipo_coluna , so they are not serialized correctly.

    
08.02.2018 / 17:52