Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache data received from an Ajax call?

I would like to cache data received from the server so that there are a minimum number of PHP/MySQL instructions executed. I know that the cache option is automatically set for $.ajax(). However, I am seeing MySQL instructions every time $.ajax() is called even if postdata is the same as it was in a 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);
    }
});
like image 254
Stephen305 Avatar asked May 01 '12 15:05

Stephen305


1 Answers

Here's the idea. Tweak it to your needs, of course.

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();
like image 90
AlienWebguy Avatar answered Sep 28 '22 09:09

AlienWebguy