Pass Ajax (X-Editable) data via $ _POST

1

I'm trying to get data from a form, where some fields I use Ajax more specifically the plugin X-Editable .

When I receive my PHP page, the following error message appears.

HTML:

    <form class="form-horizontal" id="termo8" action="procTermo.php" method="POST" target="_blank">
    <div class="panel-group">
        <div class="panel panel-success">
            <div class="panel-heading">
                <h3 class="panel-title">
                    <a data-toggle="collapse" href="#capaTermo8">08. Termo Abertura</a>
                </h3>
            </div>
            <div id="capaTermo8" class="panel-collapse collapse">
                <div class="panel-body">
                    <div class="form-group">
                        <label class="col-xs-3 control-label">Serial:</label>
                        <div class="col-xs-3">
                            <input type="text" class="form-control" name="SerialTermo8" required/>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="well text-justify well-sm">
                            Aos <a href='#' id='diaTermo8'>28</a> dias do mês de <a href='#' id='mesTermo8'>Setembro</a> de <a href='#' id='anoTermo8'>2015</a>, 
                            nesta cidade de <a href='#' id='cidadeTermo8'>CIDADE</a> – <a href='#' id='estadoTermo8'>UF</a>, realizo a abertura deste edital.
                        </div>
                    </div>
                    <div class="cleanfix"></div>
                    <button class="btn btn-inverse" name="btnGerar" value="gerar8">Gerar <span class="glyphicon glyphicon-save"></span></button>
                </div>
            </div>
        </div>
    </div>
</form>
When I click on any of these links it opens a popover so I can edit the data that is already set between <a> , when I click OK, it overrides the value.

/ p>

Ajax (X-Editable):

<script type="text/javascript">
$(document).ready(function() {      
$.fn.editable.defaults.send = "always";
$.fn.editable.defaults.url = "procTermo.php";
$.fn.editable.defaults.ajaxOptions = {type: "POST"};
$('#diaTermo8').editable({type:'text',title: 'Informe o dia'});
$('#mesTermo8').editable({type:'text',title: 'Informe o mes'});
$('#anoTermo8').editable({type:'text',title: 'Informe o ano'}); 
$('#cidadeTermo8').editable({type:'text',title: 'Informe a Cidade'});       
$('#estadoTermo8').editable({type:'text',title: 'Informe o estado'});               
});</script>

PHP (procTermo.php):

    switch ($_POST['btnGerar']) {
        case 'gerar8':

    $varMesTermo8 = $_POST['mesTermo8'];
    $varDiaTermo8 = $_POST['diaTermo8'];
    $varAnoTermo8 = $_POST['anoTermo8'];
    $varCidadeTermo8 = $_POST['cidadeTermo8'];
    $varEstadoTermo8 = $_POST['estadoTermo8'];
break;
}

When I give echo to any of these variables, it returns the error below.

Error:

  

Notice: Undefined index: mesTermo8, dayTermo8 (All same error) in /var/www/system/procTermo.php

And in print_r($_POST) , does not bring any data.

    
asked by anonymous 05.10.2015 / 22:43

1 answer

0

This happens because X-Editable , sends the parameters as associative array containing 3 values, and it will also have 3 different indexes for each of these values, see this example below, as the values passed by an X-Editable request arrive.

  

Array ([name] = > name [value] = > Default value [pk] = > 1)

Next:

  • name - corresponds to the value passed in name in the request settings.

  • value - will be the value of the edited field

  • pk - is also initialized in the first configuration.

Here is a possible solution to this problem:

$_POST[isset($_POST["name"]) ? $_POST["name"] : NULL] = isset($_POST["value"]) ? $_POST["value"] : NULL;
// Isto seria a forma encurtada, talvez meio embaraçada, mas fica simplicida no script.

Or this form here, written on blocks of multiple lines:

if(isset($_POST)){
    if(isset($_POST["name"])){
        if(isset($_POST["value"])){
            $_POST[$_POST["name"]] = $_POST["value"];   
        }   
    }   
} else {
    $_POST = NULL;  
}

Both of these would work fine, and as I said, this can be one of several solutions, if it's the most recommended, I already do not know, because I've never used this plugin before.

After writing / copying one of these codes to your script, you can simply read the variables $_POST in the usual way, without having to indicate more than one position in the array.

echo $ _POST ["mesTermo8"]; // It will return the value contained therein.

As I said before, I have never used the plugin in reference, in case you think you can improve or circumvent this hack there, feel free.

Example:

HTML

<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
        <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
        <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script><scriptsrc="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
        <link href="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/css/bootstrap-editable.css" rel="stylesheet"/>
        <script src="//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/js/bootstrap-editable.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function(){
                //Edição em linha
                $.fn.editable.defaults.mode = 'inline';
                // Definir o tipo de passagem, por omissão é POST
                // colocar novamente como eu fiz é praticamente forçar
                // Ainda assim não afecta em nada
                $.fn.editable.defaults.ajaxOptions = {type: "POST"};
                // Um único campo, vai ser editado neste exemplo.
                $('#nome').editable({
                    type: 'text',
                    pk: 1,
                    nome: 'nome',
                    url: 'editar.php',
                    title: 'Digite o novo nome',
                    /*
                     * Caso queiras confirmas se realmente teve efeito
                     * Ou ainda se quiseres saber o que o PHP retornou
                     * Utiliza-se o "success" para isto
                     *
                    success: function(retorno_do_php, novo_valor){
                        $("#stat").html("Retorno do PHP: " + retorno_do_php + "<br/> Novo valor: " + novo_valor + "<br/>");
                    }*/

                });

            });
        </script>
    </head>

    <body>
    <!-- Se quiseres adicionar alguma mensagem retornada pelo script PHP
         Descomenta esta tag
    <div id="stat"></div>
    !-->
    Nome: <a href="#" id="nome">Nome</a>
    </body>
</html>

PHP

// Configuração
if(isset($_POST)){
    if(isset($_POST["name"])){
        if(isset($_POST["value"])){
            $_POST[$_POST["name"]] = $_POST["value"];   
        }   
    }   
} else {
    $_POST = NULL;  
}

// variavel $nome recebendo o valor de $_POST normalmente
$nome = $_POST["nome"];

// Ficheiro se quer escrever
$filename = 'database.txt';

// Condições para escrever no ficheiro selecionado
// Exemplo tirado da página do php.net > fputs
if (file_exists($filename)) 
{
    $count = file('database.txt'); 
    $fp = fopen("database.txt", "w");
    fputs ($fp, $nome ."\r\n");
    fclose ($fp);
} 

else 
{
    $fh = fopen("database.txt", "w");
    if($fh==false)
    die("Sem permisao no diretorio");
    fputs ($fh, $nome ."\r\n");
    fclose ($fh);
    $count = file('database.txt'); 
}

References

X-Editable - vitalets

    
06.10.2015 / 00:16