how to pass a value of an input with ajax and receive in php with the post method?

2

I needed to pass a value of a field html to ajax and receive it in a variable in php on another page

<script>
    $(document).ready(function(){
        $("#botao").click(function(){
            site = $("#codigo").val();
            alert(site);
            $.ajax({
                url: "upload.php?acao="+site,
                type: 'POST',
                success: function(res) {
                    alert(res);
                }
            });
        });
    });
</script>

<form>
    <input type="button" class="btn btn-primary" value="Configurar" onClick="webcam.configure()">
    &nbsp;&nbsp;
    <input type="button" id="botao" class="btn btn-warning" value="Tirar Foto" onClick="take_snapshot()">
    &nbsp;&nbsp;
    <input type="button" class="btn btn-danger" value="Reset" onClick="webcam.reset()">
    &nbsp;&nbsp;
    <input type="text" placeholder="Digite o codigo" class="input-medium" id="codigo" name="codigo" value="" style="height: 35px; border-radius: 5px;" />
</form>
<div id="upload_results"></div>

PHP

$foto = @$_POST['acao'];

$uploadDir = 'paciente';

if(!is_dir($uploadDir)){
    if (!mkdir($structure, 0777, true)) {
        print "ERRO: Não foi possível criar o diretório [paciente]";
    }
}

if(!is_writable($uploadDir)){
    chmod($uploadDir, 0777);
}

$name = $uploadDir.'/image_'.$foto.'.jpg';
$file = file_put_contents($name, file_get_contents('php://input'));
if (!$file) {
    print "ERRO: Falha de escrita para o arquivo [$name], É necessário dar permissão de escrita na pasta [$uploadDir]\n";
    exit();
}

print 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI']).'/'.$name;
    
asked by anonymous 03.12.2016 / 02:07

1 answer

0

You should get the field and send it to the page, however you can send it dynamically or with a ready form

Let's say you have a ready form just store it in a variable and launch the request with the following method.

var data = $("#id_do_form").serialize();

If it is in a separate input, it will have to send dynamically.

var valor = $(".input").val();

                        var formulario = document.createElement('form');
                        formulario.id = 'sendFormFunc';

                        var input1 = document.createElement('input');
                        input1.value = valor;
                        input1.name = 'cod';

                        formulario.appendChild(input1);

                        document.body.appendChild(formulario);

                        var data = $('#sendFormFunc').serialize();

                        document.body.removeChild(formulario);

After that the request

$.ajax({
            type : "POST",
            url  : "seuarquivo.php",
            data : data,
            dataType: "json",
            success :  function(response){


            if(response.codigo == 0){alert("sucesso")}else{alert("erro")}

}

})

PHP

    $cod = (isset($_POST['cod'])) ? $_POST['cod'] : '';

    if(empty($cod)){
      $retorno = array('codigo' => 1);
    echo json_encode($retorno);
    exit();
    }
    else{
      $retorno = array('codigo' => 0);
    echo json_encode($retorno);
    exit();
    }
    
03.12.2016 / 03:05