0

Hello once again SO users :)

I have made a json string which should work with the chart (actually it works, but only when I do a hardcoded copy-paste instead of runtime work), but sadly the series won't render.

I was trying few things:

  • checking the variable scopes
  • paste the JSON data as it would be hardcoded (it works then, but it's not the solution)
  • checking if the JSON string is valid (JSON.parse() gives true)
  • doing some sleep-style functions (it didn't help)

    This is my JS code (I would use jsfiddle, but there is a $.get from DB so I can't do it :(

    <script type="text/javascript">
    $("#clickMe").click(function(event){
        $.get( '../action/jsonHChart.php', 
            {   productName: 'Snickers' }, 
                function (jsonData) { $("#jsonBug").val(jsonData); }
            );
            $("#hc_container").highcharts({
                chart: {
                     renderTo: 'hc_container'
                  },
                series: [{
                    name: 'Price',
                    data: $("#jsonBug").val() // using variable won't help either
                }]
            });
    });
    </script>
    

Edit: Transforming the code to use highcharts in $.get callback didn't help.

Yet another not working version (just FYI)

<script type="text/javascript">
$("#clickMe").click(function(event){
    $.get( '../action/jsonHChart.php', 
        {   productName: 'Snickers' }, 
            function (jsonData) { $("#hc_container").highcharts({
            chart: {
                 renderTo: 'hc_container'
              },
            series: [{
                name: 'Price',
                data: jsonData
            }]
        }); }
        );
});
</script>

Here is the link to demo of the problem, the code is quite clean (some bootstrap meta and head tags are left)

http://nowshop.pl/libs/page/a.php

You can view the full code with firebug

Bartłomiej Sobieszek
  • 2,692
  • 2
  • 25
  • 40
  • You have to put the Highcharts call *inside* the `$.get()` callback. `$.get()` is **asynchronous**, so the call returns long before the HTTP request completes. – Pointy Aug 28 '15 at 18:01

2 Answers2

1

You have to move the code that sets the data to the chart inside the callback of the ajax call:

$("#clickMe").click(function (event) {
    $.get('../action/jsonHChart.php', {
            productName: 'Snickers'
        },
        function (jsonData) {
            $("#jsonBug").val(jsonData);
            $("#hc_container").highcharts({
                chart: {
                    renderTo: 'hc_container'
                },
                series: [{
                    name: 'Price',
                    data: $("#jsonBug").val()
                }]
            });
        }
    );
});

You are performing an async call here so $("#jsonBug").val() might be undefined until the call finishes.

taxicala
  • 21,408
  • 7
  • 37
  • 66
0

Ok I have solved this guys, first I want to give some significant informations about the JSON in JS

What is a JSON? According to official site:

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

This part is a little tricky, especially the

JSON is a text format that is completely language independent

JSON is a text format for reading in text editor or on a website, but it is not a text in JavaScript, it's an object based on text that we fetch or generate to use the data in various ways. The point why I don't really like this description is because there are languages that would allow me to use string as a JSON, or, if it would not be possible - the error would appear. The JavaScript don't care that much about that and I had to search for solution for the whole day, it's not my fault and probably nor highCharts, but somewhere somebody forgot to catch this kind of mistake (I am not sure if it should be JS engine or library desinger). You can always blame me if you want to.

You can look more for it there: http://www.ecma-international.org/ecma-262/5.1/#sec-15.12.2

// Thanks to: http://stackoverflow.com/a/3710226/2010246
function IsJsonString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

// And http://stackoverflow.com/a/22482737/2010246
function isObject(val) {
    if (val === null) { return false;}
    return ( (typeof val === 'function') || (typeof val === 'object') );
}

var Json = "[[0,1],[1,2],[2,3]]"; // in chart: [[x=0,y=1],[x=1,y=2],[x=2,y=3]]
var isCorrect = IsJsonString(Json);

console.log('a JSON string: ' + Json);
console.log('is this correct JSON: ' + isCorrect);
console.log('can I use it? ' + isObject(Json));

// Fix time
Json=JSON.parse(Json);
console.log('can I use it now? ' + isObject(Json));

http://jsfiddle.net/Lfgcha3h/

So, few more lines of wrong & good examples based on highCharts data series No example here shows any kind of error in console

Wrong - the string format won't work

data: "[[0,1],[1,2],[2,3]]"

Good - we manually parse the JSON string to object

var json="[[0,1],[1,2],[2,3]]";
data: JSON.parse(json);

Good - same as above but it's Captain Obvious line

data: JSON.parse("[[0,1],[1,2],[2,3]]");

Good - we put data hardcoded (if it's not a problem for the project). In some way this is like passing the object directly

data: [[0,1],[1,2],[2,3]]

Wrong - using eval is huge security risk so it's a never-go way

// it's so bad that I won't even try to post an example

I think that's all :)

Bartłomiej Sobieszek
  • 2,692
  • 2
  • 25
  • 40