Receive data via Ajax in PHP [duplicate]

1

I'm creating an application with React, and the backend part with PHP

I have ajax request:

pesquisaCliente(e) {

e.preventDefault();
$.ajax({
    url:'http://192.168.0.109/prontaentrega/pesquisaCliente.php',
    contentType:'application/json',
    datType:'json',
    type:'post',
    data:JSON.stringify({nome:this.state.nome}),
    success: function(cli) {

    }.bind(this)
});

}

and in the PHP part:

<?php
header('Access-Control-Allow-Origin: *'); 
header("Access-Control-Allow-Headers: Content-Type");

include 'conexao.php';

echo $_POST['nome'];

?>

But it does not show the $_POST['nome]' value

Note: You are not giving any errors because they are different servers.

    
asked by anonymous 13.08.2018 / 23:59

1 answer

1

Your problem is in the data format sent to the server. In the ajax request you say that the contentType is application/json , so PHP will not populate this in the $_POST variables, it's up to you to read what was posted and execute json_decode on the information.

Your PHP file would look like:

<?php

    header('Access-Control-Allow-Origin: *'); 
    header("Access-Control-Allow-Headers: Content-Type");

    include 'conexao.php';
    $dados = json_decode(file_get_contents("php://input")); // Assim você lê o faz o decode
    echo $dados->nome; // Acessa a propriedade nome do objeto json postado.

?>
    
14.08.2018 / 00:09