0

I am having an issue getting an Ajax Response to be used within an Object.

function cart(){
    this.items = [];

    this.addItem = function(item){
        //sorts and adds items to this.items
    }

    this.retrieveCart = function(){
        var itemArray = JSON.parse($.cookie('cartItems'));
        var itemNumbers = [];
        var outData = [];
        for(var i in itemArray){
            itemNumbers.push(i);
        }
        $.post('beta-category-ajax.html', {'get' : itemNumbers.join(",")},
        function(data){
            for(var i in data){
                var currentItemNumber = data[i].I;
                var quantity = itemArray[currentItemNumber];
                data[i].Quantity = quantity;
                outData.push(data[i]);
            }
        });
        this.addItem(outData);
    }

I want to be able to run the this.addItem(Array) while still using Ajax asynchronously I saw this thread jQuery AJAX Handling Problem but I am not if this applies to me.

Thank you all for the help ahead of time :)

Community
  • 1
  • 1
4drenaline
  • 55
  • 1
  • 8
  • possible duplicate of [Declare a javascript object. Then set properties with jQuery and Ajax](http://stackoverflow.com/questions/8287834/declare-a-javascript-object-then-set-properties-with-jquery-and-ajax) – Mark Schultheiss Mar 19 '13 at 15:27
  • http://learn.jquery.com/ajax/key-concepts/ *"A is for Asynchronous"* – Kevin B Mar 19 '13 at 15:36

1 Answers1

3

I'm not entirely clear on what you are asking, but it appears that this.addItem wouldn't work the way the code is currently written. The value of this changes in the scope of the anonymous function you're passing to $.post. Cache a reference to this in retrieveCart.

this.retrieveCart = function () {
  var self = this;
  ...
  $.post(..., function () { 
    ...
    self.addItem(outData);
  });
}
stinkycheeseman
  • 43,437
  • 7
  • 30
  • 49
  • 1
    Thanks, I just saw the thread [Declare a javascript object. Then set properties with jQuery and Ajax](http://stackoverflow.com/questions/8287834/declare-a-javascript-object-then-set-properties-with-jquery-and-ajax?rq=1) Please Close Mine as a Duplicate – 4drenaline Mar 19 '13 at 15:22
  • @4drenaline you should be able to click "Delete" – Kevin B Mar 19 '13 at 15:38