Lioo Lioo - 5 months ago 16
PHP Question

Json_encode returns string instead of object

I got a php file that do some operations with the data and then send the data in

json
format(supposedly).

Then I receive the data in a js file, using ajax. It's a cross domain operation, then I need to use jsonp.

The trouble is that I'm receiving the error


Object {readyState: 4, status: 200, statusText: "success"}
parsererror - Error: jQuery1123030211047915085665_1465277732410 was
not called(…)


which I believe that is because I'm not receiving the data as a json object but as a simple string(when I change datatype from jsonp to text it goes to the
.done
block).

What can I do to receive the data as a json object, not as a simple string?

Code:

php:

if ( $moeda ==='SEK' ){

foreach($result as $r){ //$result is an array with the result of a sql query

//here I do some verifications, that depending on the circunstance, calculate and replace
//the value of the $r['price'] field.

if($r['currency'] === "SEK"){
$valor = $r['tprice'];
$r['tprice'] = number_format($valor,2,'.','');

}else if ($r['currency'] === "BRL"){
$dat = $r['emissao'];
$valor = $r['tprice'];
$r['tprice'] = number_format( ( converteBRL_SEK($dat,$valor) ) ,2,'.','');


}else if ($r['currency'] === "USD"){
$dat = $r['emissao'];
$valor = $r['tprice'];
$r['tprice'] = number_format(( converteUSD_SEK($dat,$valor) ),2,'.','');

}else if ($r['currency'] === "EUR"){
$dat = $r['emissao'];
$valor = $r['tprice'];
$r['tprice'] = number_format(( converteEUR_SEK($dat,$valor) ),2,'.','');

}
else{
echo 'error';
}
$retorno['dados'] = $r;
// using the GET callback because I'm using jsonp.
echo $_GET['callback'] . '('.json_encode($retorno,JSON_PRETTY_PRINT).')';


}


EDIT:
I forgot to post the javascript code, here goes:

code:

function buildTableDetail(p_sts,p_ar){
$('#tb_detail').empty();
return $.ajax({
type:'GET',
crossDomain:true,
url:'http://localhost/files/montar_detail_local.php?callback=?',// I use a real url, localhost just for the example
dataType:'jsonp',
data: {area:p_ar,
st:p_sts},
beforeSend: function(){
$('#t_detail').css('opacity','1.0');
console.log(p_ar);
console.log(p_sts);
}


}).done(function(data){
//after I get the data, I build a table, and format some values here...
$('#tb_detail').empty();

console.log("AREA:"+p_ar);
for (i = 0; i < data.dados.length; i++) {
$('#tb_detail').append('<tr> <td>'+data.dados[i].proposal+
'</td><td class="h_detail old_no" >'+data.dados[i].old_no+
'</td><td class="h_detail emissao" style="white-space: nowrap;">'+data.dados[i].emissao+
'</td><td class="h_detail area">'+data.dados[i].area+
'</td><td class="h_detail country">'+data.dados[i].country+
'</td><td class="h_detail ec_name">'+data.dados[i].ec_name+
'</td><td class="h_detail distributo">'+data.dados[i].distributo+
'</td><td class="h_detail project">'+data.dados[i].project+
'</td><td>'+float2moeda(data.dados[i].tprice)+
'</td><td class="h_detail gm">'+data.dados[i].gm+
'</td><td >'+data.dados[i].prob+
'</td><td class="h_detail st">'+(data.dados[i].st).substr(0,1)+'</td></tr>');


console.log(data.dados[i].proposal);
console.log(data.dados[i].distributo);
}
})
.fail(function(data, textStatus, errorThrown){
alert("Erro na operação.");
console.log(data);
console.log(textStatus);
console.log(errorThrown);
})

}


EDIT2:

Just updated this line:

echo $_GET['callback'] . '('.json_encode($retorno,JSON_PRETTY_PRINT).')';


to this

echo $_GET['callback'] . '('.json_encode($retorno,JSON_PRETTY_PRINT).');';


and the error is not showing anymore. However, it's not entering in the
for
loop and it's not showing any data. I used
console.log(data.dados.lenght)
and it returns 'undefined' to me, so I can't loop.

Any ideas?

Answer

Try the following :

  if ( $moeda ==='SEK' ){

 foreach($result as $r){ //$result is an array with the result of a sql query

//here I do some verifications, that depending on the circunstance, calculate and replace 
//the value of the $r['price'] field.

    if($r['currency'] === "SEK"){
        $valor = $r['tprice'];
        $r['tprice'] = number_format($valor,2,'.','');

    }else if ($r['currency'] === "BRL"){
        $dat = $r['emissao'];
        $valor = $r['tprice'];  
        $r['tprice'] = number_format( ( converteBRL_SEK($dat,$valor) ) ,2,'.','');


    }else if ($r['currency'] === "USD"){
        $dat = $r['emissao'];
        $valor = $r['tprice'];
        $r['tprice'] = number_format(( converteUSD_SEK($dat,$valor) ),2,'.','');     

    }else if ($r['currency'] === "EUR"){
        $dat = $r['emissao'];
        $valor = $r['tprice'];
            $r['tprice'] = number_format(( converteEUR_SEK($dat,$valor) ),2,'.','');    

    }
    else{
        echo 'error';
    }
$retorno['dados'][] = $r;   //append to the array

}
   // using the GET callback because I'm using jsonp.
echo $_GET['callback'] . '('.json_encode($retorno,JSON_PRETTY_PRINT).');'; //echo the valid call of the callback 
Comments