c newbie
c newbie

Reputation: 5

JS: Callback is not a function inside if else statement

Callback is not being recognized in the else statement of the function when compiling using google chrome. I am getting an error in my site.js file when trying to run the following code:

function changeSetting(callback) {
    var testswitch = document.getElementById("switch");
    if (testswitch.checked) {
        $.ajax({
            type: 'GET',
            url: '/api/ct/off/changeSetting',
            cache: false,
            error: function (jqXHR, textStatus, errorThrown) {
            },
            success: function (result) {
                //No error here
                callback();
            }
        });
    }
    else if (!testswitch.checked) {
        $.ajax({
            type: 'GET',
            url: '/api/ct/on/changeSetting',
            cache: false,
            error: function (jqXHR, textStatus, errorThrown) {
            },
            success: function (result) {
                //ERROR: Callback is not recognized as a function
                callback();
            }
        });
    } else {
        return;
    }
}

The only instance of this function being called is

changeSetting(displayEmail());

Uncaught Type Error: Callback is not a function

Upvotes: 0

Views: 285

Answers (2)

user5083456
user5083456

Reputation:

The problem lies in your function call.

<script>
function changeSetting(callback) {
....
}

function displayEmail() {
  return "email displayed"; // dummy value in this case 
}
</script>

Imagine running this code for example.

changeSetting(displayEmail()); // first the display email function is evaluated

Note that we are invoking the displayEmail() function with parantheses (). This means that we're going to run it and get its return value back, whether it be undefined, or in our case "email displayed".

After evaluating the function you pass as your callback, it simplifies to something that isn't a function, hence the error. Psuedo-wise, it would "simplify" to this.

changeSetting("email displayed"); // "email displayed" is obviously not a function

To fix this, simply don't invoke the function first, pass the pointer to the function, which is simply displayEmail.

changeSetting(displayEmail);

Upvotes: 1

Shubham Sharma
Shubham Sharma

Reputation: 623

Pass only displayEmail instead of invoking it in parameter of changeSetting function

changeSetting(displayEmail);

Upvotes: 1

Related Questions