Search code examples
javascriptcallbackgetjson

$.getJSON Callback Help - Not a Function


My context is as follows:

I have a variable 'qq' - I want to assign data to this variable from an API call, and once the data has been assigned, I then use this data in a paint/binding process.

The API call and assigning to var 'qq' works fine - but I cant seem to get my callback to work - I keep getting an error: callback() is not a function

This is what my code currently looks like:

var qq = [];

// binding function - to be run after data loader has completed
function sayIamDone() {
    alert('I Am Done');
    // do data bindings with qq
}

// load data from api into var qq

function dataLoader(inp,callback) {
    let url = 'http://localhost:65232/api/layercolor/' + inp;
    console.log(url);
    $.getJSON(url,function(result) {
        qq = eval('({' + result + '})');    
        //console.log(qq);
        callback();
    });
                
}

// call data loader
dataLoader('Prov', sayIamDone());

From the above I get the following error in my chrome console:

Uncaught TypeError: callback is not a function

I have tried the following - which seems to work:

dataLoader('Prov', function () { alert('I Am Done');});

but it is not ideal in my context, as I want to call dataLoader('Prov',XXX()) where XXX() could be a number of different functions using the newly loaded values in qq

Any suggestions as to where I am missing the boat please?


Solution

  • By running dataLoader('Prov', sayIamDone()); you are passing to dataLoader the result of sayIamDone function. You have to pass it without parenthesis in order to pass the function itself.

    dataLoader('Prov', sayIamDone);