How to send JSON as a post response

2

I have page A with the following code to send a POST to page B:

function curlPost($url, $dados) {
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($dados));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

$executarPost = curlPost($url, $dados);
$resposta     = json_decode($executarPost, true);

How do I send a JSON with some data from page B (page that received POST) to page A?

    
asked by anonymous 17.11.2018 / 16:35

1 answer

1

You can use echo on the B page along with json_encode . After sending the request from A to B, A will wait for a response from B. Thus, B will use the combination of echo and json_encode to send the response in JSON format to A.

In this example I am simulating that A sends the data the data id with a value and nome_topico with another value to B. Therefore, the code from B below will respond to the same data sent by A (which can be any data defined by the developer):

B.php:

<?php

if(isset($_POST['id']) && isset($_POST['nome_topico'])) 
{
    $resposta = array(
        'id' => $_POST['id'],
        'nome_topico' => $_POST['nome_topico']
    );

    echo json_encode($resposta);
}

In your example, the response of B will be in the $executarPost variable.

    
17.11.2018 / 17:13