0

I want to get information from database and draw a chart. I have this code:

$.post("ajax.php?param=grp", {grp: grp}, function (rply) {

            var densityCanvas = document.getElementById("densityChart");

            var R = rply;
            new Chart(densityCanvas, R);


        });

Variable rply contains this:

    {
      type: "bar",
      data: {
        labels: ["pitanje 1", "pitanje 2", "Pitanje 3"],
        datasets: [
    {
        label: "Pozitivni",
        data: [5, 4, 7],
        backgroundColor: "rgba(0, 99, 132, 0.6)",
        borderColor: "rgba(0, 99, 132, 1)"
    }
    ,
    {
        label: "Negativni",
        data: [3,1, 5],
        backgroundColor: "rgba(99, 132, 0, 0.6)",
        borderColor: "rgba(99, 132, 0, 1)"
    }
    ]
    },
  options: {scales: {
        yAxes: [{
            display: true,
            ticks: {
                suggestedMin: 0, 
                beginAtZero: true
            }
        }]
    }}}

"new Chart" doesn't draw new chart unless this returned JSON is hardcoded. If it's not hardcoded browser gives an error: "Cannot create property 'data' on string...".

If I do: var R = JSON.parse(rply);

It gives me this error: "Unexpected token t in JSON at position 4".

Kreso
  • 25
  • 1
  • 8
  • 1
    sounds like rply is a string, not JSON – epascarello Apr 17 '18 at 13:45
  • Yes it is, but even if I do JSON.parse(rply) it doesn't work – Kreso Apr 17 '18 at 13:51
  • @Kreso can you provide the entire string your data base returns? "Unexpected token t in JSON at position 4". sounds like an invalid json string – Nicolas Gehlert Apr 17 '18 at 13:54
  • So does the parse() line fail if you do it? Do you get an error? Are you sure you have what you think you have? Does `console.log(rply)` have anything else with it? Your code above is not valid JSON if that is what is being returned. It lacks quotes around all the keys which is required to be valid JSON. Your code is a valid object, but it is not valid JSON. – epascarello Apr 17 '18 at 13:54
  • @NicolasGehlert this is the whole string, I copied it from console.log – Kreso Apr 17 '18 at 13:55
  • @epascarello as I wrote it gives me an error "Unexpected token t in JSON at position 4" – Kreso Apr 17 '18 at 13:56
  • I even tried return this string as JSON in PHP like this: echo json_encode($string) and then use it with and without JSON.parse() and it won't work either way – Kreso Apr 17 '18 at 13:57
  • 1
    because it is not valid JSON. It needs to be `{ "type": "bar", "data":` .... https://jsonlint.com/ – epascarello Apr 17 '18 at 13:57

1 Answers1

0

The problem with your rply JSON string is that you need to wrap your keys with " because JSON.parse(..) expects a valid JSON format which requires double quotes.

You can see a brief explanation in w3schools - JSON syntax

JSON names require double quotes. JavaScript names don't.

Here you can find a way to convert your string into a valid JSON format.

Rodrigo Ferreira
  • 1,091
  • 8
  • 11