Pass Ajax (X-Editable) data via $_POST

Asked

Viewed 453 times

1

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

When receiving in my PHP page appears the error message below.

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>

How X-Editable works, when I click on any of these links it opens a Popover so I can edit the data that is already pre-set between <a>, when finishing click OK ai replaces the value.

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 in any of these variables, returns the error below.

Error:

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

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

1 answer

0


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

Array ( [name] => name [value] => Value_de_of this [pk] => 1 )

Thereafter:

  • 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’s 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 still this shape 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 would work well, and as I said, this could be one of several solutions, if it’s the most recommended, I don’t know, because I’ve never used this before plugin before.

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

echo $_POST["mesTermo8"]; // Will return the value it contains.

Like I said, I’ve never used the plugin in reference, if you think you can improve or circumvent that hack there, feel at ease.

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> 
        <script src="//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

  • Hey, Edilson, great explanation. However even with the examples mentioned above, I did not get any value in my $_POST array, as little as I understand, it seems that when I give Ubmit in my form, all other values are sent, but only what this in Ajax does not send, this checking with print_r($_POST)

  • Edit your question, and add more detail to your script, or complete it, so I can see how it is, or store it in Pastebin.

  • See if it’s clearer Edilson.

  • There it is, an example to aid the explanation.

Browser other questions tagged

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