12

I'm trying to pass in a function to run when the AJAX call is successful, however it's not working as it say's that "callback is not a function".

Example:

Calling Code:

getGrades(var);    

JS:

function getGrades(grading_company) {

    // Set file to get results from..
    var loadUrl = "ajax_files/get_grades.php";

    // Set data string
    var dataString = 'gc_id=' + grading_company;

    // Set the callback function to run on success
    var callback = 'showGradesBox';

    // Run the AJAX request
    runAjax(loadUrl, dataString, callback);

}

function showGradesBox(response) {

    // Code here...

}

function runAjax(loadUrl, dataString, callback) {

    jQuery.ajax({
        type: 'GET',
        url: loadUrl,
        data: dataString,
        dataType: 'html',
        error: ajaxError,
        success: function(response) {
            callback(response);
        }
    });    

}

Now if I replace this line below with the function name itself it works:

callback(response);

But I can't get it to work like above where I get the function name from a passed in parameter.

3
  • 3
    You can't pass a string as a function, but if it's inside an object literal you can use bracket notation, or if it's global, you can use window[callback] to reference a variable in the global scope, and assign the function instead of using a function decleration. Commented Jan 6, 2013 at 18:39
  • 2
    On the other hand, after looking at it, just returning the promise from the ajax function, and using done() would be a lot simpler, like so -> JSBIN Commented Jan 6, 2013 at 18:47
  • @adeneo So that will only run on success? Commented Jan 6, 2013 at 18:53

1 Answer 1

15

showGradesBox is a string in your code. So you have two options to execute the callback function:

If you want to keep the string you can use

this[callback](response);

(if callback is defined in global scope you can also use window[callback](response);

Or you can pass the function directly:

var callback = showGradesBox;

(in this case you can keep your existing code for callback execution)

Sign up to request clarification or add additional context in comments.

Comments

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.