How to send JSON as a response to the post

Asked

Viewed 164 times

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 to send a JSON with some data from page B (page that received the POST) to page A?

1 answer

1


You can make use of the echo on page B together with json_encode. After sending the request from A to B, A will expect a reply from B. Therefore, B will use the combination of echo and json_encode to send the JSON-format reply to A.

In this example I am simulating that A send the data the data id with a value and nome_topico with another value for B. Therefore, the code of B below will answer 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 answer of B will be in the variable $executarPost.

Browser other questions tagged

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