Reputation: 1097
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);
}
});
Upvotes: 5
Views: 6769
Reputation: 78006
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();
Upvotes: 4
Reputation: 95063
I would handle the cache myself:
// 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');
}
});
This way, if a request with said id has already happened, a new request will not be made unless you remove it from the cache.
Upvotes: 4
Reputation: 55792
You have to add a cache parameter like:
$.ajax({
...
...
cache : true
});
Upvotes: 0