I have a fully working JS code below but it is sending POST request to the server for every click event. How is it possible to cache the AJAX post response below?
Ideally, the cache should be saved as JS variables. If it is already loaded and present in the cache, it will be displayed (without doing POST). If it’s not loaded yet, it will do a POST request and save in the cache and then display.
jQuery( document ).ready( function( $ ) {
var _doing_ajaxx = false;
$('.toolbar').remove();
$('#mydiv #frontend').click(function() {
if (_doing_ajaxx) {
return false;
}
var title_shortcode = $(this).text();
var insert_namex= $(this).attr('class');
var titlejsselector=title_shortcode.replace(/ /g,'');
var buttonval=$('#'+titlejsselector+' input').val();
if (buttonval=='Minimize') {
//stop ajax request if button is set
$('#'+titlejsselector+' div').remove();
$('#'+titlejsselector+' input').remove();
} else {
//initialize ajax variables
var data = {
action: 'test_ajax_response',
test_ajax_response_nonce: the_ajax_script.test_ajax_response_nonce,
postID_from_ajax : the_ajax_script.postid_to_ajax,
insert_name_ajax: insert_namex,
title_ajax: title_shortcode
};
//do an ajax request
_doing_ajaxx = true;
$.post(the_ajax_script.ajaxurl, data, function(response) {
$(this).next().slideToggle();
$('#mydiv #'+titlejsselector).append(response+"<input type='hidden' id='minimizebutton' value='Minimize'>");
SyntaxHighlighter.highlight();
$('.toolbar').remove();
_doing_ajaxx = false;
});
}
//return false;
});
});
I tried adding this code using PHP and it does not work:
<?php
header("Cache-Control: private, max-age=$seconds");
header("Expires: ".gmdate('r', time()+$seconds));
?>
If someone can provide some sample code to get started, I would gladly appreciate it. Thanks.
If you want to cache from within the JS (so if they reload the page, the cache will no longer be there), I’d create an object and store the results:
Then, when you’re about to send the request:
Untested, but you should get the idea 🙂