Skip to content

Instantly share code, notes, and snippets.

@syaiful-scooter
Forked from teknosains/sample-menu-view.php
Created March 14, 2020 14:26
Show Gist options
  • Save syaiful-scooter/30f46e858aa5e44349a1d4af371c979a to your computer and use it in GitHub Desktop.
Save syaiful-scooter/30f46e858aa5e44349a1d4af371c979a to your computer and use it in GitHub Desktop.
<h3>List Menu</h3>
<span class="loading"></span>
<div id="menu">
<!--menu di render disini-->
</div>
<button type="button" id="logout">Logout</button>
<script src="<?php echo base_url('assets/js/jquery-3.4.1.min.js'); ?>"></script>
<script>
/**
* jQuery Ready
*/
$(function() {
function renderMenuToStorage() {
const ajaxObject = {
url: 'http://localhost/spm/Menu/GetMenu',
type: 'GET', dataType: 'json',
beforeSend: function() {
$(".loading").html("Loading menu");
},
success: function(response) {
if (response.status == true) {
console.log(response);
// remove/clear storage fist sebelum kita tulis/Set
// make sure aja biar clean write ke localstorage
localStorage.removeItem('menu');
// comvert json to string first
let menux = response.menu;
// save to browser localStorage
localStorage.setItem('menu', menux);
// hide loading indicator
$(".loading").html("");
renderMenutoHtml();
}
}
};
// call ajax nya
$.ajax(ajaxObject);
}
function renderMenutoHtml() {
let menu = localStorage.getItem('menu');
if (menu) {
$("#menu").html(menu);
}
}
// call the function
// check jika menu tidak ada di localStorage, maka ambil ke database
if (!localStorage.getItem('menu')) {
renderMenuToStorage();
} else {
renderMenutoHtml();
}
// event listeners
$("#logout").click(function() {
// clear storage
localStorage.removeItem('menu');
// destroy session
setTimeout(function(){
window.location.href = 'http://localhost/spm/logout';
}, 1000);
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment