javascriptajaxjsonprotovis

Syntax:Error JSON.parse, When trying to load data for protovis


Hi I'm learning how to work with protovis, so far so good, but now I stumbled upon a problem I can't seem to solve.

The following is the code. (I have the latest jquery loaded in my headers)

<script type="text/javascript+protovis"> 
var dataURL = "http://eagereyes.org/media/2010/protovis-primer/earthquakes.json";

var JSONdata = $.ajax({ type: "GET", url: dataURL, async: false }).responseText;
var earthquakes = JSON.parse(JSONdata);

var width = 560;
var height = 245;

var barWidth = width/earthquakes.length;
var gap = 2;

new pv.Panel().width(width).height(height+5)
    .add(pv.Bar)
        .data(earthquakes)
        .bottom(0)
        .width(barWidth-gap)
        .height(function(d) d.Magnitude * (height/9))
        .left(function() this.index * barWidth)
    .root.render();

When I try this in Firefox i get this alert:

Syntax:Error JSON.parse

I have validated the JSON on http://www.jsonlint.com/ already. So the problem must be elsewhere.

Anyone knows whats going on here?

Edit

I tried loading the same data in the protoviewer app: http://www.rioleo.org/protoviewer/ and it works. So it must be the code.


Solution

  • Have you tried a regular async callback instead of the synchronous approach? Like:

    var dataURL = "http://eagereyes.org/media/2010/protovis-primer/earthquakes.json";
    
    $.ajax({
      type: "GET",
      url: dataURL,
      success: function(response) {
        var earthquakes = JSON.parse(JSONdata);
    
        var width = 560;
        var height = 245;
    
        var barWidth = width/earthquakes.length;
        var gap = 2;
    
        new pv.Panel().width(width).height(height+5)
            .add(pv.Bar)
                .data(earthquakes)
                .bottom(0)
                .width(barWidth-gap)
                .height(function(d) d.Magnitude * (height/9))
                .left(function() this.index * barWidth)
            .root.render();     
      }
    });
    

    Also, is that JSON file located on the same server that the page making the request shows in the address bar (exactly http://eagereyes.org)?

    Finally, the manual JSON.parse() step isn't necessary. If you add the dataType: 'json' parameter, $.ajax() will automatically deserialize as JSON and uses JSON.parse() where available.