How to cache data received from an Ajax call?

I would like to cache the data received from the server so that the minimum number of PHP / MySQL instructions is executed. I know that the cache parameter is automatically set for $ .ajax (). However, I see MySQL statements every time $ .ajax () is called, even if postdata is the same as in the previous call. Am I missing something? What is the best way to cache data received from the server? Here is my code:

var postdata = {'pid':'<?php echo $project_id;?>',
                'record_id':this.id};

$.ajax({
    type: "POST",
    url: "get_note.php",
    data: postdata
}).done(function(data){
    if (data != '0') {
        // Add dialog content
        $('#note_container').html(data);
        $('#note_container').dialog();
    } else {
        alert(woops);
    }
});
+5
source share
3 answers

Here is an idea. Of course, customize it to your needs.

function getAjaxData(){
    var $node = $('#note_container');
    if ($node.data('ajax-cache').length == 0) {
        $.ajax({
            // do stuff. 
            success: function(data){
                // Add dialog content
                $node.html(data).data('ajax-cache',data).dialog();
            }
        });
    } else {
        $node.html( $node.data('ajax-cache') ).dialog();
    }
}
getAjaxData();
+4
source

I myself would handle the cache:

// declare this on global scope
var ajaxCache = {};
...

if (!ajaxCache[this.id]) {
    ajaxCache[this.id] = $.ajax({
        type: "POST",
        url: "get_note.php",
        data: {'pid':'<?php echo $project_id;?>','record_id':this.id}
    });
}

ajaxCache[this.id].done(function(){
    if (data != '0') {
        // Add dialog content
        $('#note_container').html(data);
        $('#note_container').dialog();
    } else {
        alert('woops');
    }
});

Thus, if a request with the specified identifier has already occurred, the new request will not be executed if you do not remove it from the cache.

+4

, :

$.ajax({
...
...
cache : true
});
0

All Articles