0

I have created a generic function that gets data from the server via jQuery's AJAX call. When successfully retrieving the data, I'd like to call another function that I'm passing in (e.g. functionAfterSuccess in the below code example).

This passed in function is getting called, but it seems to be executing right away and not "waiting" until the successfully retrieving the data from the server.

Does the passed in function (functionAfterSuccess) get executed at the same time as the main function (genericAJAXGet)? Not sure what I'm doing wrong.

// calling function
$('#run').on('click' , function() {

    var $url = '/getdata';
    var $dataToSend = { id: '123', data: 'ABC' };

    genericAJAXGet("POST", $url, $dataToSend, "json", myFunction($param1));

});

// generic AJAX function
function genericAJAXGet($type, $url, $dataToSend, $returnDataType, functionAfterSuccess) {

    // build ajax request
    var $request = $.ajax({
                    type: $type,
                    url: $url,
                    data: $dataToSend,
                    dataType: $returnDataType
                });

    // Process a successful response
    $request.done(function(data) {

        if(data.error) {

            alert('uh oh');

        } else {

            // successfully returned data, but there was some application logic
            if (data["type"] == "issue") {

                alert('app logic issue');

            } else {

                // only run the passed in function when the data is successfully retrieved
                functionAfterSuccess;
            }
        }

    });

    // Process a failed response
    $request.fail(function() {
        alert('request failure');

    });
}

// Other function to be called that is being passed in as a parameter
function myFunction($param1) {

    alert($param1);

}

1 Answer 1

3

You're probably (saying probably, because you never showed how you call the main function) not passing the function, but the function return value:

genericAJAXGet($type, $url, $dataToSend, $returnDataType, myFunction()) {

Instead, it should be:

genericAJAXGet($type, $url, $dataToSend, $returnDataType, myFunction) { // <--- no parentheses

And then, in your code, call it like this:

        } else {

            // only run the passed in function when the data is successfully retrieved
            functionAfterSuccess(); // parentheses needed here to actually call it
        }

Also, you probably want to check whether functionAfterSuccess exists and is a function.


UPDATE

If you wish to send parameters to the callback function as well, you might add another parameter to the main call:

genericAJAXGet("POST", $url, $dataToSend, "json", myFunction, $param1);

Then change its definition to:

function genericAJAXGet($type, $url, $dataToSend, $returnDataType, functionAfterSuccess, functionParam) {
... 
}

And finally, to call it from inside the function:

} else {

        // only run the passed in function when the data is successfully retrieved
        functionAfterSuccess(functionParam); // now the parameter is inside the parentheses
    }

To make it clearer, this is the function with the relevant change inside:

function genericAJAXGet($type, $url, $dataToSend, $returnDataType, functionAfterSuccess, functionParam) {
    ... 
    } else {

        // only run the passed in function when the data is successfully retrieved
        functionAfterSuccess(functionParam); // now the parameter is inside the parentheses
    }
    ...
}

And this is how you call it (with the arguments from your example):

var $url = '/getdata';
var $dataToSend = { id: '123', data: 'ABC' };
myFunction = function(p) {
     alert(p);
}
var $param1 = 'Hey there!';
genericAJAXGet("POST", $url, $dataToSend, "json", myFunction, $param1);
Sign up to request clarification or add additional context in comments.

7 Comments

I added some more code to better explain the situation.
@shawnzizzo And it's exactly what I described, try to follow my method. (genericAJAXGet("POST", $url, $dataToSend, "json", myFunction);)
OK... I'm a bit slow on this. Apologies. When would myFunction be called? I'm not seeing how myFunction and functionAfterSuccess are related.
No problem, I should've probably written the whole functions, but I'll try to explain: myFunction is the function you pass in as an argument/parameter when you make the call, while functionAfterSuccess is the name of the function argument/parameter.
What if I wanted to pass in a different function into the genericAJAXGet function and have that executed where functionAfterSuccess is being executed? For instance, let's say I now have function myFunction2($param2) { console.log('this works!: ' +$param2)}; And now I would have genericAJAXGet("POST", $url, $dataToSend, "json", myFunction2, $param2); Again, my goal is to be able to pass in any function into genericAJAXGet and only have that passed in function execute under certain conditions.
|

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.