Ajax does not send data to PHP

Asked

Viewed 70 times

-2

I have the following code in Ajax:

<script>
    $('#enviar').click(function() {   
        let dados
        let filtros = document.getElementsByName('filtro[]');
        let filtrosvalidos = [];
        filtros.forEach(function(elemento, index){
            if(elemento.checked){
                filtrosvalidos.push(elemento.value)
            }
        })
        let pesquisa = document.getElementById('pesquisa').value
        let pesquisa2 = document.getElementById('pesquisa2').options[document.getElementById('pesquisa2').selectedIndex].value
        let horaatual = document.getElementById('horaatual').value
        $.ajax({
            type : "POST",
            url : "pesquisar.php",
            crossDomain: true,      
            contentType: "application/json; charset=utf-8",
            //dataType: 'json',       
            data:{
                    filtro: JSON.stringify(filtrosvalidos),
                    pesquisa: JSON.stringify(pesquisa),
                    pesquisa2: JSON.stringify(pesquisa2),
                    horaatual: JSON.stringify(horaatual),
            },
            success : function(responseData, textStatus, jqXHR) {
                // dados = JSON.parse(responseData)
                // processarDados(dados)
                console.log(responseData);
            }
});

});

And in php, the following code:

<?php

echo 'ok';
echo json_decode($_POST['filtro']);

?>

However, nothing leaves the console when I return php echo to ajax. Does anyone know why?

  • print_r(json_decode($_POST['filtro']));

  • That’s not the problem, because json_decode returns a string, so echo would work the same way. But still, I test print_r and it returns me saying that the index 'filter' is undefined. If I put echo ($POST) it returns me an empty array, so I said on the question that I suspect that ajax is not sending the data to PHP.

  • https://www.php.net/manual/en/function.json-decode.php

1 answer

0


I found the solution. I switched POST to GET, both in ajax code and PHP code and it worked.

Browser other questions tagged

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