Ryan
Ryan

Reputation: 787

Resetting AJAX data held in cache

Each time I make an AJAX call, the results are being cached in the browser as expected. However, previous results are interfering with the most recent call, and unexpected actions are occurring within my web app.

I have tried to set cache as false, but that doesn't appear to have any effect. How do I reset AJAX data so that only the most recent call can be used?

function getProductDetails(selected, obj) {
    if (obj)
        obj.abort();
    }

    var url = <url>;

    //Request
    obj = $.ajax({
        url: url,
        method: 'post',
        cache: false,
        data: {
            action: action,
            frontend: frontend,
            selected: selected
        }
    });

   obj.done(function(data) {
       var items = JSON.parse(data);
       ...
   });
}

$(document).on('ready', function() {
    selected = $('.selected').html();
    var products = getProductDetails(selected, obj);

    $('.tabs-nav li').each(function(){
        $(this).on('click', function(){
            products = getProductDetails(selected, obj);
        });
    });
}

Upvotes: 1

Views: 46

Answers (1)

epascarello
epascarello

Reputation: 207501

My guess is the Ajax code is perfectly fine. The problem is

$('.tabs-nav li').each(function(){
    $(this).on('click', function(){
        products = getProductDetails(selected, obj);  <---
    });
});

Do you want the selected to be what you clicked on? Also it makes no sense to pass obj around.

My guess is you want

var obj;
function getProductDetails(selected) {

    if (obj)
        obj.abort();
    }

    var url = <url>;

    //Request
    obj = $.ajax({
        url: url,
        method: 'post',
        cache: false,
        data: {
            action: action,
            frontend: frontend,
            selected: selected
        }
    });

   obj.done(function(data) {
       var items = JSON.parse(data);
       ...
   });
}

$(document).on('ready', function() {
    var selected = $('.selected').html();
    var products = getProductDetails(selected);

    $('.tabs-nav li').each(function(){
        $(this).on('click', function(){
            products = getProductDetails(this.innerHTML);
        });
    });
}

Upvotes: 1

Related Questions