1

I have an ajax call to several different services. I know my array var log is being overwritten by each successive call, but I can't figure out how to change the logic to append the next array instead of overwriting.

$.ajax($.extend({}, ajaxDefaults, source, {
                data: data,
                success: function(events) {
                    events = events || [];
                    var res = applyAll(success, this, arguments);
                    if ($.isArray(res)) {
                        events = res;
                    }
                    callback(events);


                  var log = log || [];
                      for (var i=0; i<events.length; i++) {
                        log.push(events[i]);
                    }
                    console.log(log);

                },
                error: function() {
                    applyAll(error, this, arguments);
                    callback();
                },
                complete: function(events) {
                    applyAll(complete, this, arguments);
                    popLoading();

                }
            }));

1 Answer 1

4

This is just a problem of scope. You're redeclaring 'var log' inside of the $.ajax success() function (and thus overwriting it). Declare var log outside of $.ajax and just push the new results into that array.

Try the following:

var log = [];
$.ajax($.extend({}, ajaxDefaults, source, {
    data: data,
    success: function(events) {
        events = events || [];
        var res = applyAll(success, this, arguments);
        if ($.isArray(res)) {
            events = res;
        }
        callback(events);

        for (var i=0; i<events.length; i++) {
            log.push(events[i]);
        }
        console.log(log);

    },
    error: function() {
        applyAll(error, this, arguments);
        callback();
    },
    complete: function(events) {
        applyAll(complete, this, arguments);
        popLoading();

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

3 Comments

yes the var log = log || []; creates a new object each time
thank you! That makes sense. I thought var log = log || []; would create a new log if log was undefined.
Using a global variable would work: log = log || []; It's just when you redeclare the variable with 'var log' that you're overwriting it.

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.