JSON returns STRING instead of ARRAY

Asked

Viewed 387 times

0

The following code is returning an array as a string and therefore I cannot distribute the data to popular Flot Chart.

The

PHP code:

<?php

include_once("config.php");

$viagemid = $_POST['id'];
$results_array = array();

$sql = "SELECT adiantamento AS 'Antecipado' FROM viagem WHERE viagemid = $viagemid";
$query = $mysqli->query($sql);
while($row =mysqli_fetch_assoc($query)){

    array_push($results_array, $row);
}

$sql = "SELECT SUM(vl_desp) as 'Despesas' FROM despesas WHERE viagemid = $viagemid";
$query = $mysqli->query($sql);
while($row =mysqli_fetch_assoc($query)){

    array_push($results_array, $row);
}


$sql = "SELECT SUM(venda.vl_venda * venda.qtd) AS 'Venda SP' FROM venda WHERE venda.viagemid = $viagemid AND venda.ufid = 1";
$query = $mysqli->query($sql);
while($row =mysqli_fetch_assoc($query)){

    array_push($results_array, $row);
}

$sql = "SELECT SUM(venda.vl_venda * venda.qtd) AS 'Venda local' FROM venda WHERE venda.viagemid = $viagemid AND venda.ufid = 2";
$query = $mysqli->query($sql);
while($row =mysqli_fetch_assoc($query)){

    array_push($results_array, $row);
}



$string = "[[0,".$results_array[0]['Antecipado']."],[1,".$results_array[1]['Despesas']."],[2,".$results_array[2]['Venda SP']."],[3,".$results_array[3]['Venda local']."]]";


var_dump(json_decode(serialize($results_array), true));

?>

THE JS:

    $(function() {

        $.post('chart_data.php', {id:<?php echo $viagemid; ?>}, function(data) {

            alert(data);
            var d1 = [[0,data],[1,data],[2,data],[3,data]];

            alert(d1);

        var barOptions = {
            series: {
                bars: {
                    show: true,
                    barWidth: 0.6,
                    fill: true,
                    align:'center',
                    fillColor: {
                        colors: [{
                            opacity: 0.8
                        }, {
                            opacity: 0.8
                        }]
                    }
                }
            },
            xaxis: {
                tickDecimals: 0,
                ticks:[[0,'Adiantamento'],[1,'Despesas'],[2,'Venda SP'],[3,'Venda local']]
            },
            colors: ["#ffbb00"], 
            grid: {
                color: "#999999",
                hoverable: true,
                clickable: true,
                tickColor: "#D4D4D4",
                borderWidth:0
            },
            legend: {
                show: false
            },
            tooltip: true,
            tooltipOpts: {
                content: "%x: %y"
            }

        };
        var barData = {
            label: "bar",
            data: d1
        };
        $.plot($("#flot-bar-chart"), [barData], barOptions);

    });

        //return false;
});
  • What is the return of JSON?

  • 1

    Are you using the var_dump to send to Javascript? Strip and place echo.

  • @Marcelodeandrade after using var_dump(json_decode( it from the error (json_decode expects Parameter 1 to be string), so I used serialize() to convert to string and then returned NULL and with echo it returns "[{"Anticipated":"30000"},{"Expenses":"18256.61"},{"Sale SP":"13080"},{"Local sale":"18021.5"}]"

  • 1

    Why are you Serializing? No need, it worked normally giving json_decode in this return, see in ideone

1 answer

1


Some points to consider:

1) No need to execute 4 querys and travel them repeatedly with while. You can make only one select and use the fetch_all of mysqli.

2) How did you not explain the intention of using the serialize, I see no use in him for that.

include_once("config.php");

$viagemid = $_POST['id'];
$results_array = array();

$sql = <<<SQL
SELECT
(SELECT adiantamento  FROM viagem WHERE viagemid = {$viagemid}) AS 'Antecipado',
(SELECT SUM(vl_desp) FROM despesas WHERE viagemid = {$viagemid}) AS 'Despesas',
(SELECT SUM(venda.vl_venda * venda.qtd) FROM venda WHERE venda.viagemid = {$viagemid} AND venda.ufid = 1) AS 'Venda SP',
(SELECT SUM(venda.vl_venda * venda.qtd) FROM venda WHERE venda.viagemid = {$viagemid} AND venda.ufid = 2) AS 'Venda local' 
SQL;

$query = $mysqli->query($sql);
$result = $query->fetch_all(MYSQLI_ASSOC);


echo json_encode($result, true);

On your call ajax, informed the dataType: JSON, see the options here :

Altere of:

$.post('chart_data.php', {id:<?php echo $viagemid; ?>}, function(data) {

To:

$.ajax({
  type: "POST",
  url: 'chart_data.php',
  data: {id:<?php echo $viagemid; ?>},
  dataType: "json",
  sucess: function(data) {
     alert(data);
        var d1 = [[0,data],[1,data],[2,data],[3,data]];

        alert(d1);

    var barOptions = {
        series: {
            bars: {
                show: true,
                barWidth: 0.6,
                fill: true,
                align:'center',
                fillColor: {
                    colors: [{
                        opacity: 0.8
                    }, {
                        opacity: 0.8
                    }]
                }
            }
        },
        xaxis: {
            tickDecimals: 0,
            ticks:[[0,'Adiantamento'],[1,'Despesas'],[2,'Venda SP'],[3,'Venda local']]
        },
        colors: ["#ffbb00"], 
        grid: {
            color: "#999999",
            hoverable: true,
            clickable: true,
            tickColor: "#D4D4D4",
            borderWidth:0
        },
        legend: {
            show: false
        },
        tooltip: true,
        tooltipOpts: {
            content: "%x: %y"
        }

    };
    var barData = {
        label: "bar",
        data: d1
    };
    $.plot($("#flot-bar-chart"), [barData], barOptions);
  }
});
  • Thanks Marcelo, but he keeps returning json_decode expects Parameter 1 to be string. And thanks also for the organization of the code, I made several querys to go testing.

  • I corrected the answer, the correct function is json_encode. Take the test again.

  • I was searching and fell into json_encode, by coincidence. It passed to the JS, but all in one string: [{"Anticipated":null,"Expenses":"6000","Sale SP":"14240","Local sale":"900"}]

  • But the format is correct, isn’t it? You should add the type: JSON in his ajax request or give a JSON.parse()

  • Yes, that’s exactly it. Can you describe the syntax of JSON.parse? I’m reading about it right now but I’m having a hard time adapting to my code.

  • See the example I entered in the reply.

  • Marcelo, thank you so much for your help. I ended up not changing to Ajax as you suggested (I couldn’t) but I learned to use JSON.parse and I was able to convert to object.

  • Great that you understood the operation and solved the problem.

Show 3 more comments

Browser other questions tagged

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