Ajax based add and delete items for storing user settings in LocalStorage using jQuery

Updated on September 1, 2017

In this following webmaster guide, i will be showing you, how to accept user input, store, retrieve and delete in Local Storage using jQuery. In the demo and download, i will be requesting for RSS Feed URL, which i will be validating and upon success will store and retrieve for display. User can delete it at any point of time, which happens through AJAX.

Example 1 : You all would have used Facebook commenting ! Once the comment is posted, on hover a close button shows up, upon clicking, the comment gets deleted. Such close action i will be showing you in the following guide.

Example 2 : Similarly while developing Google Chrome Extensions, some extensions requires user inputs. To store such inputs, you can use local Storage for storing and deleting which i will be showing you in the following guide.

Store Retrieve Delete from LocalStorage using Ajax jQuery
Store Retrieve Delete from LocalStorage using Ajax jQuery

[sc:demobuttons demolink=”http://demo.techglimpse.com/store-retrieve-delete-from-localstorage-using-jQuery/” boxlink=”http://adf.ly/PkqbX”]

Step 1 :

Include the below CSS Style Sheet in your HTML Head section. This is for the text, plus(+) and close(x) buttons.

.right{ 
width:16px; 
height:25px; 
background: url('add.png') no-repeat; 
opacity:0.3; 
margin:7px 0px 0px 140px ; 
cursor:pointer;
-webkit-transition-duration:500ms; 
}
.right:hover { opacity:1.0; }
.close{
width:16px; 
height:25px; 
background: url('close.png') no-repeat; 
opacity:0.3; 
margin:2px 0px 0px 140px ; 
cursor:pointer;
-webkit-transition-duration:500ms; }
.close:hover { opacity:1.0; }
.left{ 
height:25px; 
float:left; 
margin-top:5px; 
text-shadow: 1px 1px white, -1px -1px #598ede; 
font-family: Lora; 
font-size: 1.3em; 
margin-left: -250px;
}

Below style sheet for the popup window.

.poppup_overlay{ 
display: none;
position:fixed;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
background-position:fixed;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.poppup_overlay { 
/* ie6 hack */ position: absolute;
height: expression(document.body.scrollHeight > 
document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); 
}
.poppup_content {
display: none;
position:absolute;
left: 25%;
padding: 10px;
/*border: 1px solid orange; */
background-color: white;
z-index:1002;
overflow: auto; 
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
height: auto;
width: auto;
}
.poppup_content { /* ie6 hack */position: absolute;
margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px');
}
.header-close {
padding: 6px 0px;
border-bottom: 1px solid #eee;
}
.span_title { 
font-size: 1.5em;
font-weight: bold;
width: 630px;
display: inline-block;
}
.span_close { 
float: right;
font-size: 1.5em;
font-weight:bold;
}
#fb_div { float:left; margin-top: 20px;}
#fb_div2 { float:left;margin-left: 50px;margin-top: 20px;}
#addedDisplay { float:left; margin-top: 15px; }

Step 2 :

Include the below Javascript code and the jQuery. In the Javascript code, i have included the comments for each function and the block of code.

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Function to generate random key to store data on Local Storage
function randomStr(m) {
 var m = m || 9; s = '', r = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
 for (var i=0; i < m; i++) { s += r.charAt(Math.floor(Math.random()*r.length)); }
 return s;
};


Function to extract Domain name alone from the URL

 function getHost(url) {
 var a = document.createElement('a');
 a.href = url;
 var str = a.hostname;
 var regex = /www./;
 return str.replace(regex, "");
}


Function to create PopUP window

 function showLightBox() {
 document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block';
 document.getElementById('light').innerHTML = '<div class="header-close"><span class="span_title">Tell us to serve you better</span><span class="span_close"><a href = "javascript:void(0)" onclick = "document.getElementById(\'light\').style.display=\'none\';document.getElementById(\'fade\').style.display=\'none\'" style="text-decoration:none;">X</a></span></div>';
 document.getElementById('light').innerHTML += '<div id="fb_div"><label>Add RSS Feed URL : </label><input size="50" type="text" name="name" id="fb_name" autofocus="autofocus" value="http://"></div>';
 document.getElementById('light').innerHTML += '<div id="fb_div2"><button value="Submit" id="fb_submit" >Submit</button></div>';
 }
function close_popup() {
 document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none';
}

// On Document Ready, i am checking for the existence of localStorage. On success, if it is first time, create an Object and store it as JSON object in the localStorage. Display all the items stored already. On clicking addition button, show the popup window for input from the user. Upon Input from the user, check for the validity of the RSS Feed and on success, store it in the LocalStorage and display the updated stored results. Upon delete button click, remove the item from the storage and display the updated stored results.

 $(document).ready(function(){
// This block of code is to check for the availability of LocalStorage in the Browser. Also if available, then create a JSON object with "myfeeds" as key. 
 var hasStorage = true;
 if(!localStorage.getItem("myfeeds")) {
 var hasStorage = (function() {
 try {
 var myRSSObject = new Object();
 localStorage.setItem("myfeeds", JSON.stringify(myRSSObject));
 return true;
 } catch(e) {
 return false;
 }
 }());
 }
// This block of code is to check for the availability of LocalStorage in the Browser. Also if available, then create a JSON object with "myfeeds" as key. 

// This code is to display the already stored data on the browser.
 document.getElementById('addedDisplay').innerHTML = '';
 var myfeeds = JSON.parse(localStorage.getItem("myfeeds"));
 for(var key in myfeeds)
 {
 document.getElementById('addedDisplay').innerHTML += '<div id="' + key + '" style="float:left;word-wrap:break-word;width:140px;">' + getHost(myfeeds[key]) + '</div><div id="closeBtn" class="close"></div>';
 }
// This code is to display the already stored data on the browser.

// This button click function is to show the popup window
 $("#addBtn").click(function() {
 showLightBox();
 });
// This button click function is to show the popup window

// This Future generated button click function is to get the RSS Feed URL and added it to the Local Storage
 $("#light").on("click", "#fb_submit", function() {
 fb_name = document.getElementById("fb_name").value;
 if(fb_name =='') {
 alert("Message Null");
 } else {
 // If the input is not null, then check for the validity of the RSS feed and if valid store else, display proper Error Message.
 var pipesURL = "http://pipes.yahoo.com/pipes/pipe.run?_id=6e4bee80587070e6eef12cd53b720009&_render=json&urlinput1=" . concat(fb_name);
 $.ajax({
 type: "GET",
 url: pipesURL,
 dataType: "json",
 success: function(xml) {
 if(xml.count > 0 ) {
 if(hasStorage) {
 var myfeeds = JSON.parse(localStorage.getItem("myfeeds"));
 var n = randomStr(7);
 myfeeds[n] = fb_name;
 localStorage.setItem("myfeeds", JSON.stringify( myfeeds ));
 document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none';
 var myfeeds = JSON.parse(localStorage.getItem("myfeeds"));
 document.getElementById('addedDisplay').innerHTML = '';
 for(var key in myfeeds)
 {
 document.getElementById('addedDisplay').innerHTML += '<div id="' + key + '" style="float:left;word-wrap:break-word;width:140px;">' + getHost(myfeeds[key]) + '</div><div id="closeBtn" class="close"></div>';
 }
 } else {
 alert("Storage Failed. Try refreshing");
 }
 }
 else {
 alert("Feed URL is wrong. Verify and ADD");
 document.getElementById('fb_name').value = "http://";
 document.getElementById('fb_name').focus();
 }
 }
 });
 }
 });
// This Future generated button click function is to get the RSS Feed URL and added it to the Local Storage

// This future generated close button click function is to delete the corresponding Stored Items.
 $("#addedDisplay").on("click", "#closeBtn", function() {
 var delete_id = $(this).prev("div").attr('id');
 var myfeeds = JSON.parse(localStorage.getItem("myfeeds"));
 delete myfeeds[delete_id];
 localStorage.setItem("myfeeds", JSON.stringify( myfeeds ));
 document.getElementById('addedDisplay').innerHTML = '';
 for(var key in myfeeds)
 {
 document.getElementById('addedDisplay').innerHTML += '<div id="' + key + '" style="float:left;word-wrap:break-word;width:140px;">' + getHost(myfeeds[key]) + '</div><div id="closeBtn" class="close"></div>';
 }
 });
// This future generated close button click function is to delete the corresponding Stored Items.
});

Step 3 :

Include the below code in the body of the HTML template.

	<div class="left">Add your RSS</div>
		<div class="right" id="addBtn"></div>
		<div id="addedDisplay"></div>
		<div class="arrow"></div>
		<div id="light" class="poppup_content"> </div>
		<div id="fade" class="poppup_overlay" onclick="close_popup()"></div>

[sc:demobuttons demolink="http://demo.techglimpse.com/store-retrieve-delete-from-localstorage-using-jQuery/" boxlink="http://adf.ly/PkqbX"]

Was this article helpful?

Related Articles

Leave a Comment