0

Here is what I'm struggling with today:

I'm trying to draw a graph using jqPlot library. The sql query outputs data which is converted to json in php by using json_encode and saved in hidden form field. This works fine and the actual field contains:

[["2011-12-10 12:01:00",271],["2011-12-10 12:13:05",132],["2011-12-11 12:17:55",388],["2011-12-10 22:03:40",5],["2011-12-11 12:10:54",830]]

Then the data from the form is retrieved in javascript by using:

var data = document.getElementById("dataarray").value;

in order to use it as a data for jqPlot later on. The data variable is correctly formatted and when checked with document.write(data);, outputs correct data in json format but whenever I place it inside the plot1 variable to use data for the graph it throws an error [object Object] in Safari and Uncaught #<Object> in Firefox.

The whole javascript code is as follows:

$(document).ready(function(){

    var data = document.getElementById("dataarray").value;  


    var test = [["2011-12-10 12:01:00",271],["2011-12-10 12:13:05",132],["2011-12-11 12:17:55",388],["2011-12-10 22:03:40",5],["2011-12-11 12:10:54",830]];
    var plot1 = $.jqplot("chart_personal_2", [data], {
          title:"Data Point Highlighting",
          axes:{
        xaxis:{
          renderer:$.jqplot.DateAxisRenderer,
          numberTicks: 3,
          tickOptions:{
            formatString:"%d/%m/%Y %H:%M:%S"
          } 
        },
        yaxis:{
        label: "Elevation(m)",
          tickOptions:{
             showMark: true
            }
        }
          },
          highlighter: {
        show: true,
        sizeAdjust: 7.5
          },
          cursor: {
        show: false
          }
      });
});

I even tried output = String(data); but it did not work either. I'm assuming that my data variable is an object that cannot be used as source data for jqPlot graph, it needs to be converted to string prior use? Correct me if I'm wrong.

Hope somebody knows how to work it out without, thanks in advance!

1 Answer 1

4

You are retrieving it as String, but jqPlot expect Array, so you have to run eval on it:

var data = document.getElementById("dataarray").value;
eval('data = '+data+';');

or better solution: don't save it to hidden input, but make JS variable from php:

echo "<script type='text/javascript'> var data = ".json_encode($data).";</script>";
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, converting it to an array fixed the issue. I was quite sure that jqPlot is also able to handle string if it is in JSON format, but I can see I was wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.