Catch JSON after submitting a POST

Asked

Viewed 756 times

2

I’m having trouble getting the answer I have after sending a request via POST

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

After that I wanted to take this answer that I have in JSON and "separate" the fields that I have as return, for example:

$resposta = httpPost($url, $data);

$status = $resposta->{'status'};

Answer I get when I execute:

{"errors":[{"type":"internal_error","parameter_name":null,"message":"Ocorreu um erro ao cancelar a transferência."}],"url":"URL","method":"post"}

I wanted to print "message" for example.

2 answers

1


I got it this way:

$executar_transf = httpPost($url, $data);
$resposta_fin = json_decode($executar_transf, true);

echo $resposta_fin['errors']['0']['message'];

0

A hint is to use the function $.get() jquery:

$(function () {
    $.get('exemplo.php', {
        //parametros da solicitacao
        param: 'pamametro'
    },function (data) {
        // resposta da solicitacao
        var response = data['errors'];
        console.log(response[0].message);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

One detail is that if you want to send more than one parameter, just separate them by comma: { param_1: 'param_1', param_2: 'param_2' }

Browser other questions tagged

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