Add parameters in JSON array after form serialize

Asked

Viewed 238 times

1

After giving the following command in Javascript:

var dados = $("#form-historico").serialize();

Is it possible to add more information to the object? for example: I would like to send along with the POST data some parameters to recover in PHP file (table, column, etc)...

I tried something like that, but it didn’t work out so well:

    var dados = $("#form-historico").serialize();
    myPost = {
        "dados": dados,
        "param": [
            {
                "crud" : "create",
                "table" : "tbl_historicos"
            }
        ]
    }

Sending only serialized data and giving a print_r($_POST), print this way in PHP:

Array
(
    [hist_peso] => dfs
    [hist_altura] => fsf
    [hist_pa] => sfsf
    [hist_fc] => sfs
    [hist_op] => fs
    [hist_temp] => fsfsf
    [hist_id_paciente] => 3
    [hist_id_usuario] => 1
    [hist_id] => 
    [hist_data_cadastro] => 
    [hist_prontuario] => fsfsff
    [hist_tratamento] => fsfsfs
    [hist_obs] => 
    [hist_reacao_alergica] => 
    [hist_doenca_contagiosa] => 
    [hist_mpa] => 
    [hist_etilismo] => 
    [hist_tricotomia] => 
    [hist_cardiopatia] => 
    [hist_protese] => 
    [hist_outras_doencas] => 
    [hist_jejum] => 
    [hist_tabagismo] => 
    [hist_diabetico] => 
    [hist_insulina] => 
    [hist_outros_exames] => 
)

But by including the other parameters in the array and giving a print_r($_POST), print this way:

Array
(
    [dados] => hist_peso=&hist_altura=&hist_pa=&hist_fc=&hist_op=&hist_temp=&hist_id_paciente=3&hist_id_usuario=1&hist_id=&hist_data_cadastro=&hist_prontuario=&hist_tratamento=&hist_obs=&hist_reacao_alergica=&hist_doenca_contagiosa=&hist_mpa=&hist_etilismo=&hist_tricotomia=&hist_cardiopatia=&hist_protese=&hist_outras_doencas=&hist_jejum=&hist_tabagismo=&hist_diabetico=&hist_insulina=&hist_outros_exames=
    [param] => Array
        (
            [0] => Array
                (
                    [crud] => create
                    [table] => tbl_historicos
                )

        )

)

If anyone can help me or tell me where I’m going wrong???

2 answers

2

I think this example fits you.

//EVENTO PARA QUANDO SUBMITAMOS O FORMULÁRIO DE CADASTRO
$('#formulario-cadastro').submit(function(e) {
  e.preventDefault();


  let origem = "pagina-de-cadastro";
  let formulario = $("#formulario-cadastro");
  cadastrar(formulario, origem);


});

function cadastrar(formulario, origem) {

  $.ajax({
    url: "php/cadastro.php",
    type: "post",
    data: formulario.serialize() + '&variavel=' + encodeURIComponent(origem),


  }).done(function(data) {


  }).fail(function() {

  });

}

  • Above, we have a form with ID "#registration form". We add this form to a variable (called form).
  • We also have a variable (called origin) that receives a String.
  • Then we pass this variable and the form as a parameter to the function register(), and we call this function.
  • Within that function we have a AJAX that sends this data (both the variable origin when the serialized form) for the PHP.

In the PHP you would receive the variable by POST. Behold:

<?php

 $variavel_que_recebe = $_POST['variavel'];

?>

OBS: If you want to send more variables together, just put as below:

data: formulario.serialize() + '&variavel=' + encodeURIComponent(origem) + '&variavel_2=' + encodeURIComponent(origem_2)

  • Above, you would send the variables origin and origem_2.

  • To receive in the PHP:

<?php

  $variavel = $_POST['variavel'];
  $variavel_2 = $_POST['variavel_2'];  
  
?>

  • Yes, very good this example! That way I tried and got, however it concatenates more information in JSON. I needed something to help me separate this information when retrieving in the PHP file, for example: $data = $_POST['data'] and $parametros = $_POST['parameters']... I’ll try here, or it will be via URL even the parameters, but I believe there is a way to do this, I think!!! But thanks for the force...

  • I supplemented the answer. Take a look.

  • @Rdamazio , in this example, you would receive the variables, which you are sending in AJAX, by POST in PHP. Type $_POST['variavel']. That would not be your need ?

  • Yeah, I just tested your example, it really works. The problem is that I have a class that assembles the SQL statement with the parameters that comes in this POST, in this case it will end up assembling these additional fields too, which in turn do not exist in the database table... Only if I assemble a function to mount the array disregarding these parameter variables neh...

  • But you don’t want the variables coming in PHP by Post ? Your question seemed that way...

  • Yes, I would like to send everything via POST, with the form data as well as the parameters to control in the PHP file

  • So this is happening with this code. i am not getting a right understanding of what you would like to do with these values, who arrive by post, in the php file.

  • If the answer was useful to you, and answered your question explicitly in the question, you can accept by clicking the button located to the left of the answer.

Show 4 more comments

1


I was able to solve it this way:

Page with HTML form and Javascript

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>JSON | PHP | SERIALIZE</title>
        <link rel="stylesheet" type="text/css" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css">
        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="https://mdbootstrap.com/api/snippets/static/download/MDB-Pro_4.12.0/css/mdb.min.css">
    </head>
    <body>
        
        <div class="container d-flex justify-content-center mt-5">

            <!-- Extended default form grid -->
            <form id="form-dados-paciente">
                <!-- Grid row -->
                <div class="form-row">
                    <div class="form-group col-md-2">
                        <label for="id">Código</label>
                        <input type="text" class="form-control" id="id" name="id">
                    </div>
                    <div class="form-group col-md-2">
                        <label for="data_cadastro">Data do Cadastro</label>
                        <input type="text" class="form-control" id="data_cadastro" name="data_cadastro">
                    </div>
                    <div class="form-group col-md-6">
                        <label for="nome_paciente">Nome Paciente</label>
                        <input type="text" class="form-control" id="nome_paciente" name="nome_paciente">
                    </div>
                    <div class="form-group col-md-2">
                        <label for="cpf">CPF</label>
                        <input type="text" class="form-control" id="cpf" name="cpf">
                    </div>
                    <div class="form-group col-md-2">
                        <label for="data_nascimento">Data de Nascimento</label>
                        <input type="text" class="form-control" id="data_nascimento" name="data_nascimento">
                    </div>
                    <div class="form-group col-md-2">
                        <label for="sexo">Sexo</label>
                        <select class="browser-default custom-select form-control" id="exo" name="sexo">
                            <option value=""></option>
                            <option value="Masculino">Masculino</option>
                            <option value="Feminino">Feminino</option>
                        </select>
                    </div>
                    <div class="form-group col-md-6">
                        <label for="nome_mae">Nome da Mãe</label>
                        <input type="text" class="form-control nome-proprio" id="nome_mae" name="nome_mae">
                    </div>
                    <div class="form-group col-md-2">
                        <label for="telefone">Telefone</label>
                        <input type="text" class="form-control" id="telefone" name="telefone">
                    </div>

                </div>
                <!-- Grid row -->
                <button class="btn-enviar btn btn-info justify-content-center">Enviar</button>
            </form>
            <!-- Extended default form grid -->

        </div>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    </body>

    <script>

        $(".btn-enviar").click(function () {
            
            //serializando os dados do formulário
            var dados = $("#form-dados-paciente").serializeArray();
            
            //criando o objeto JSON com os parametros
            var param = {
                "param" : {
                    "option" : "gravar",
                    "tabela" : "tbl_pacientes",
                    "coluna" : "id",
                    "switch" : "editar-paciente"
                }
            };
            
            //fazendo chamada AJAX
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                
                //usando $.param para enviar em formato de array
                //e concatenando os objetos DADOS e PARAMETROS
                data: $.param(dados) + "&" + $.param(param),
                success: function (res) {
                    console.log(res);
                }
            });
            return false;
        });

    </script>

</html>

In the archive ajax.php:

  • I retrieved and assigned the POST data in a variable $arrPosts

    //recuperando e atribuindo os dados do POST a variável
    $arrPosts = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

  • I created a function to clear the parameters and create a new array only with the form data

//chamando a função para limpar os dados dos parametros
//e passando a variável com os dados do POST como parametro
$arrDados = limpaDadosParametros($arrPosts, array());

//Função para iterar o array montar um novo array somente
//com os dados do formulário enviados via POST
function limpaDadosParametros($arrPosts, $arrDados) {
    foreach ($arrPosts as $key => $value) {
        if (($key != "param")) {
            $arrDados[$key] = $value;
        }
    }
    return $arrDados;
}

  • Printing the new arrays

    echo '<br>Dados Form';
    echo '<pre>';
    print_r($arrDados);//imprimindo os dados do novo array
    echo '</pre>';
    echo '<br>Parametros';
    echo '<pre>';
    print_r($arrPosts['param']);//imprimindo os dados de parametros
    echo '</pre>';

I got the expected values:

Dados Form
Array
(
    [id] => 000014
    [data_cadastro] => 20/09/2019 10:36:24
    [nome_paciente] => Marcio da Silva Pereira
    [cpf] => 632.154.587-88
    [data_nascimento] => 15/03/1988
    [sexo] => Masculino
    [nome_mae] => Marcia da Silva Pereira
    [telefone] => (15) 3217-7083
)

Parametros
Array
(
    [option] => gravar
    [tabela] => tbl_pacientes
    [coluna] => id
    [switch] => editar-paciente
)

  • Complete file ajax.php

<?php

if ((filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING))) {
    
    //recuperando e atribuindo os dados do POST a variável
    $arrPosts = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
    
    //chamando a função para limpar os dados dos parametros
    //e passando a variável com os dados do POST como parametro
    $arrDados = limpaDadosParametros($arrPosts, array());

    echo '<br>Dados Form';
    echo '<pre>';
    print_r($arrDados);//imprimindo os dados do novo array
    echo '</pre>';
    echo '<br>Parametros';
    echo '<pre>';
    print_r($arrPosts['param']);//imprimindo os dados de parametros
    echo '</pre>';
}

//Função para iterar o array montar um novo array somente
//com os dados do formulário enviados via POST
function limpaDadosParametros($arrPosts, $arrDados) {
    foreach ($arrPosts as $key => $value) {
        if (($key != "param")) {
            $arrDados[$key] = $value;
        }
    }
    return $arrDados;
}

Browser other questions tagged

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