Print json return text in the middle of code - Jquery/Javascript/JSON

Asked

Viewed 967 times

1

I have a chart that is created according to the year, which is passed by AJAX and returns a JSON containing the values to create the chart. Well, I send the AJAX with the year, return the JSON, however... It gives error, it creates everything wrong, follow my code.

My controller where I return the data and create the JSON:

public function comparativo_json(){
    $html = '';
    $data = $this->relatoriosmodel->getComparativo($this->input->post('ano'));

    $html .= '[';
    foreach($data['mesesFuncionario'] as $func):
        $html .= "{";
            $html .= "name: '".$data['funcionarioDados'][$func['id']]->nome."',";
            unset($func['id']);
            $html .= "data: [ "; foreach($func as $f){ $html .= $f.','; } substr($f,-1); $html .= "]";
        $html .= "},";
    endforeach; 
    $html .= ']';

    echo json_encode($html);
}

My JS:

<script type="text/javascript">
$(function(){
    $('#ano').change(function(){
        $.ajax({
            url: '/relatorio/comparativo_json',
            type: 'POST',
            dataType: 'json',
            data: {ano: $("#ano option:selected").val()},
            success: function(data){

                $('#containerHighCharts').highcharts({
                    title: {
                        text: 'Comparativo de Vendas',
                        x: -20 //center
                    },
                    subtitle: {
                        text: 'Ano de Referência: '+$("#ano option:selected").val(),
                        x: -20
                    },
                    xAxis: {
                        categories: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun',
                            'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez']
                    },
                    yAxis: {
                        title: {
                            text: 'Reais (R$)'
                        },
                        plotLines: [{
                            value: 0,
                            width: 1,
                            color: '#808080'
                        }]
                    },
                    tooltip: {
                        valueSuffix: ' (R$) Reais'
                    },
                    legend:{
                        layout: 'vertical',
                        align: 'right',
                        verticalAlign: 'middle',
                        borderWidth: 0
                    },
                    series: data,
                });
            }
        });
    });
}); 
</script>

The JSON it returns, which by the way is correct, as requested by the plugin:

[
    {
        name: 'Richard Feliciano',
        data: [ 0,0,0,0,1816,17100,2400,0,0,0,0,0,]
    },
    {
        name: 'Ewerton Melo',
        data: [ 0,0,0,0,0,12400,0,0,0,0,0,0,]
    },
]

Image containing the error:

inserir a descrição da imagem aqui

I just need to make the return data be printed correctly.

  • The problem is specifically in the impression of series: data,

  • 1

    The only thing I can think of is that I’m forgetting to do the JSON.parse, 'Cause otherwise it feels good: http://jsfiddle.net/yb3Nt/ Test like this: series: JSON.parse(data), Test also console.log(data); or console.log(typeof data); and comment here on what you get.

  • I did the console.log(typeof data); and he returns as string, just below did the parse var dataJSON = JSON.parse(data) and returned error: Uncaught SyntaxError: Unexpected token n

  • In fact it must be the JSON conversion of this string

  • Okay, and what you get if you do console.log(data); ?

  • [{name: 'Richard Feliciano',data: [ 0,0,0,0,1816,17100,2400,0,0,0,0,0,]},{name: 'Ewerton Melo',data: [ 0,0,0,0,0,12400,0,0,0,0,0,0,]},]

  • It returns the pattern of the JSON straight, but as string. I tried JSON.parse(data) or $.parseJSON(data) and the error is the same as in the above comment...

  • And if you stop to analyze, I give json_encode() right at the return of the value.

  • I also tried the JSON.stringify(data) that as I looked in some forums also serves to convert string into JSON, however, it keeps as string. I did straight only to test console.log(typeof JSON.stringify(data)); but still continues as string.

  • Either you create an array/object and use json_encode() or you create a string and do not use Encode. In the case of the second option (which is what you are doing), quote " around the key, and value that is string, of each object. And remove the extra commas. Then this string will be accepted by JSON. Take a look here: http://jsfiddle.net/n3ARn/

  • @Sergio, thank you so much for your help, but the tips below solved the problem. Thank you so much for your willingness to help. A hug.

Show 6 more comments

1 answer

1


There’s a problem here:

foreach($data['mesesFuncionario'] as $func):
    $html .= "{";
        $html .= "name: '".$data['funcionarioDados'][$func['id']]->nome."',";
        unset($func['id']);
        $html .= "data: [ "; foreach($func as $f){ $html .= $f.','; } substr($f,-1); $html .= "]";
    $html .= "},";
endforeach;

The json string format cannot have a comma at the end, it only separates the objects. Follow the example you gave:

[{name: 'Richard Feliciano',data: [ 0,0,0,0,1816,17100,2400,0,0,0,0,0,]},{name: 'Ewerton Melo',data: [ 0,0,0,0,0,12400,0,0,0,0,0,0,]},]

He should be:

[{name: 'Richard Feliciano',data: [ 0,0,0,0,1816,17100,2400,0,0,0,0,0,]},{name: 'Ewerton Melo',data: [ 0,0,0,0,0,12400,0,0,0,0,0,0,]}]

Note that I removed the last comma. I don’t understand PHP, but what you need to do is check so that it doesn’t add the last comma.

After you fix this just use JSON.parse(data); it will work perfectly.

  • You may still have problems not using double quotes, but check this out... if you have a problem with parse, switch to double quotes in your JSON string: [{name: "Richard Feliciano",date: [ 0,0,0,0,1816,17100,2400,0,0,0,0,0,0,]},{name: "Ewerton Melo",date: [ 0,0,0,0,12400,0,0,0,0,0,0,0,0,0,0,0,]}]

  • Thank you very much I used the PHP function substr($html,0,-1) to remove the last element of the string at the points where it ended with , and worked perfectly, returned the chart.

  • 1

    I’m glad it worked out. With JSON strings it is very important to keep the correct format when converting to an object in a given language. You can also try using standard PHP methods to form JSON strings instead of writing the string by hand, this makes your code less error-prone!

Browser other questions tagged

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