POST variables are null when sending data from App Inventor Web component to PHP

I'm developing a shopping cart system using MIT App Inventor, integrated with PHP and MySQL. When I click a button in the app to add a product to the cart, I'm using the Web2 component to make a POST request to a PHP script hosted on my server.

The problem is: when I send the data from App Inventor, the PHP script receives null values for the expected $_POST variables.

However, when I test the same request using Insomnia (see attached image), it works perfectly and returns the correct success response.

Issue:
When making the same request from App Inventor, the $_POST['codigo_cliente'], $_POST['codigo_produto'], and $_POST['quantidade'] are all null on the PHP side.
php responsecode:
if (is_null($codigoCliente) || is_null($codigoProduto) || is_null($quantidade)) {
http_response_code(400);
echo json_encode(["status" => "erro", "mensagem" => "Parâmetros insuficientes: 'codigo_cliente', 'codigo_produto' e 'quantidade' são obrigatórios."]);
exit();
}

POST php variables:
header('Content-Type: application/json');
$codigoCliente = isset($_POST['codigo_cliente']) ? $_POST['codigo_cliente'] : null;
$codigoProduto = isset($_POST['codigo_produto']) ? $_POST['codigo_produto'] : null;
$quantidade = isset($_POST['quantidade']) ? $_POST['quantidade'] : null;

blocks:

Single post request is enough

set Web1.PostText to "codigo_cliente=" + codigo_cliente_value + "&codigo_produto=" + codigo_produto_value + "&quantidade=" + quantidade_value

Instead of looking into $_POST, you can read the raw input and decode JSON:

header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);

$codigoCliente = isset($data['codigo_cliente']) ? $data['codigo_cliente'] : null;
$codigoProduto = isset($data['codigo_produto']) ? $data['codigo_produto'] : null;
$quantidade = isset($data['quantidade']) ? $data['quantidade'] : null;

if (is_null($codigoCliente) || is_null($codigoProduto) || is_null($quantidade)) {
    http_response_code(400);
    echo json_encode(["status" => "erro", "mensagem" => "Parâmetros insuficientes: 'codigo_cliente', 'codigo_produto' e 'quantidade' são obrigatórios."]);
    exit();
}

You can add error logging in your PHP script to see what data is actually being received. This can help you troubleshoot if the request is malformed:

file_put_contents('debug.log', print_r($_POST, true), FILE_APPEND);
1 Like

thank so much! saved my university project!

1 Like