Value not being taken via POST

2

No index.php has 1 field input that sends a value by ajax , which should be read by cdb.php .

index.php:

<script type="text/javascript">
        $(document).ready(function(){
            $("#formulario").on("submit", function(e){
                e.preventDefault();
                var cdb = $("#cdb").val();
                $.ajax({
                    url: "cdb.php",
                    method: "POST",
                    dataType: "html",
                    data: cdb
                }).done(function(data){
                    $("#cdb").val("");
                    $("#cdb").focus();
                    listar();
                }).fail(function(data){
                    alert("Erro");
                });
            });
        });
</script>

...

<form id="formulario" method="POST" action="" accept-charset="utf-8">
        <div>
            <?php echo rand(1, 100) ?>
            <input id="cdb" type="text" name="cdb" class="validate" required autofocus onfocus="this.value='';">
            <button type="submit">GRAVAR</button>
        </div>
</form>

cdb.php

$cdb = filter_input(INPUT_POST,'cdb');
    
asked by anonymous 17.01.2018 / 13:29

1 answer

3

The problem is that you are passing information without reference at all. The data property of the ajax gets a array of type key and value , that is, for each item it is necessary to have a key and a value, in your code you are only passing cdb , to pass the key also you could do something like:

$("#formulario").on("submit", function(e){
    e.preventDefault();
    var cdb = $("#cdb").val();
    $.ajax({
    url: "cdb.php",
        method: "POST",
        dataType: "html",
        data: {
            cdb: cdb
        }
    }).done(function(data){
        $("#cdb").val("");
        $("#cdb").focus();
        listar();
    }).fail(function(data){
        alert("Erro");
    });
});

But if your form had more fields, you would have to do it one by one. To our delight there is a function that is responsible for taking all the fields of a form and transform it into an array of type key and value , in which case key will be the name property of the field and value will be value of the field itself. This function is the serialize() to use it would be simply like this:

$("#formulario").on("submit", function(e){
    e.preventDefault();
    var cdb = $("#cdb").val();
    $.ajax({
    url: "cdb.php",
        method: "POST",
        dataType: "html",
        data: $("#formulario").serialize()
    }).done(function(data){
        $("#cdb").val("");
        $("#cdb").focus();
        listar();
    }).fail(function(data){
        alert("Erro");
    });
});
    
17.01.2018 / 13:48