Receiving data via Ajax in PHP

Asked

Viewed 1,026 times

1

I’m creating an application with React, and the back-end 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'];

?>

Only he doesn’t show the value of $_POST['nome]'

Note: There is no error because they are different servers.

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, soon PHP will not popular this in the variables $_POST, it is up to you to read what has been posted and run the json_decode in the information.

Your PHP file would look:

<?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.

?>
  • he ta showing it on the screen: Trying to get Property of non-object

  • Okay. Execute echo file_get_contents("php://input"), Tell me what appears printed.

  • That’s right, the problem is that ajax is waiting for a return json, and since I was just printing the variable in php, it returned html. I think it should be the Act that requires this.

  • Great, I’m glad you caught the problem.

Browser other questions tagged

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