How to access json from Rest API

Dirty

New Member
#1
I am returning data from a rest API. I was getting the header along with the json, but as Justin T. pointed out below I needed to add this to my cURL:
Mã:
curl_setopt( $ch, CURLOPT_HEADER, 0);
That got rid of the header. Now I am having issue with the returned json and the encoding of it(I think)
Mã:
if ( $httpCode != 200 )
{
    echo "Return code is {$httpCode} \n".curl_error($ch);
}
 else {
    $output = json_encode($result);
    echo($output);
}
and my jQuery
Mã:
$.ajax({
    type:$('#BTA_AddUser').attr('method'),
    url: form.action,
    data: dataString,
    dataType:"json",
    success: function(data){
        if(data) {
            $('#response').html(data);
        } else {
            $('#response').html('<p>no response</p>');
        }
    }
});
This prints out the returned json on the page:
Mã:
{"code":"UserUpdated","status":200,"message":"OK","payload":{"email":"test@test.com","expired":null,"funded":true}}
however, I cannot access the json objects, using
Mã:
success:function(data){
    if(data.code == "UserUpdated"){
     //do something
    }
}
It defaults to the else clause, not doing what is inside when looking for data.code
 

Admin

Administrator
Thành viên BQT
#2
You need to set your CURLOPT_HEADER to false. This will exclude the plain-text header information from the response.
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top