syui syui - 3 months ago 24
Ajax Question

Ajax syntax : Uncaught SyntaxError: Unexpected identifier

I am getting this


Uncaught SyntaxError: Unexpected identifier error


, Why ? I think i have used the syntax properly ?

// I've revised it
var json;
json = '{"1438905600":0,"1438992000":0}';
setTimeout( $('#example-heatmap').each(function() {
if( json != null ){
var obj = $.parseJSON(json);
var now = new Date();
new CalHeatMap().init({
data: obj,
start: new Date(2016, 0),
cellSize: 11,
range: 9,
domain: 'month',
domainLabelFormat: '%Y-%m',
itemSelector: '#example-heatmap',
legend: [1, 3, 5, 7],
legendColors: {
min: '#efefef',
max: 'steelblue',
empty: '#efefef'
},
tooltip: true
//start: new Date(now.getFullYear(), now.getMonth() - 9)
});
} else {
setTimeout( arguments.callee, 100 );
}
}));

Answer

You are passing a call to jQuery#each into setTimeout, but setTimeout expects a function or a string containing a JavaScript code block. jQuery#each returns neither.

The value returned is being converted to the string [object Object] and this is what's causing the syntax error.

To fix this, create a lambda function to contain your call to jQuery#each:

setTimeout(function() {
    $('#example-heatmap').each(function() {
        if (json != null) {
            var obj = $.parseJSON(json);
            var now = new Date();
            new CalHeatMap().init({
                data: obj,
                start: new Date(2016, 0),
                cellSize: 11,
                range: 9,
                domain: 'month',
                domainLabelFormat: '%Y-%m',
                itemSelector: '#example-heatmap',
                legend: [1, 3, 5, 7],
                legendColors: {
                    min: '#efefef',
                    max: 'steelblue',
                    empty: '#efefef'
                },
                tooltip: true
                    //start: new Date(now.getFullYear(), now.getMonth() - 9)
            });
        } else {
            setTimeout(arguments.callee, 100);
        }
    });
});

I must say, however, that what you are doing looks very hacky. You're using arguments.callee, which is now deprecated, apparently in some attempt to "wait" on an asynchronous operation. You should instead handle the asynchrony properly, using callbacks or promises.

Comments