How to concatenate a javascript object to a post form?

Asked

Viewed 216 times

1

I have an object JSON that I built at runtime, I need it sent to my servlet, along with the other form fields, via post, how do I do this? I searched 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");
        }
    });
});

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

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

My object is as follows:

inserir a descrição da imagem aqui

Thanks in advance!

  • what console.log(layoutColunas) prints if you put just before return layoutColunas;?

  • @merchant he prints the exact same JSON object as Return

1 answer

1


According to the function documentation jQuery.param()

If the Object passed is in an Array, it must be an array of Objects in the format returned by .serializeArray()

Translating

if past object is in a array, he must be a array of objects in the format returned by .serializeArray()

Example of the required format:

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

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

  • Cool, I’ll try it here!!!

  • name=Base1234&connection=1234&phone=34234&typeBase=1&client name=1&Cpf=2. It worked, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.