Question

I have a function, which makes an ajax request and returns and array of 3 values. This function is later called in another function, then following error appears:

Uncaught TypeError: undefined is not a function

When I change the first line into function two to: array = one(); it works exactly one time, every other function call ends in followiing error:

Uncaught TypeError: object is not a function

Can anyone please explain me, how it comes to these two errors!?


My code:

function one() {
        var result = null;
         var scriptUrl = [...];
         $.ajax({
            url: scriptUrl,
            type: 'get',
            dataType: 'html',
            async: false,
            success: function(data) {
                [...]
                val1 = [...];
                val2 = [...];
                val3 = [...];
            }
         });
         return [val1, val2, val3];
    }

 function two() {
            var array = one();
            var val5 = array[0];
            var val6 = array[1];
            var val7 = array[2];
        }
Was it helpful?

Solution

changed my code to following (working):

function one(callback) {
        var result = null;
         var scriptUrl = [...];
         $.ajax({
            url: scriptUrl,
            type: 'get',
            dataType: 'html',
            success: function(data) {
                [...]
                var val1 = [...];
                var val2 = [...];
                var val3 = [...];
                var result = [val1, val2, val3];
                callback(result);
            }
         });
    }

function two(result) {
    var val1_from_ajax = result[0];
    var val2_from_ajax = result[1];
    var val3_from_ajax = result[2];
}

one(two);

Fast explanation:
The result of my ajax-call is passed to success, where the result is processed. After that the function, which is based on the processed return values from ajax, is directly called (bringing along these values). The function which is based on the ajax return values, is passed by a paremeter, so in my example, I call one(two); which means callback(result); inside the success is two(result);
Hope this clarifies it a bit :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top