ExtJS 5.1 Remember Me on local store - javascript

I'm trying to do Remember Me with an interesting algorithm. I was thinking, when i click the Remember Me and Login, the value of the text fields (username&password) will be saved as a default value. My login button click event here:
var username = Ext.getCmp('setNo').getValue();
var password= Ext.getCmp('setPass').getValue();
if(refs.checkStudent.value === true){
Ext.getCmp('setNo').setValue(username);
Ext.getCmp('setPass').setValue(password);
}
else{
Ext.getCmp('setNo').setValue("");
Ext.getCmp('setParola').setValue("");
}
On console, it is working. But I'm working with a local store, no server. So when i refresh the page, it's gone. Is there a way to not lose them?

on your view onAfterRender event:
Ext.getCmp('setNo').setValue(localStorage.username);
Ext.getCmp('setPass').setValue(localStorage.password);
on your button click event:
if (refs.checkStudent.value === true) {
localStorage.username = Ext.getCmp('setNo').getValue();
localStorage.password = Ext.getCmp('setPass').getValue();
} else {
localStorage.removeItem('username');
localStorage.removeItem('password');
}

Use ExtJs utility to set and get values in cookies. At time of login set
username and password in cookies and after refresh the page read username
and password value from the cookie.
Ext.util.Cookies.set('username', username); // To set value in cookie.
Ext.util.Cookies.get('username'); // to get value form cookie.

Related

How to restart a unended game in the middle? [duplicate]

I am trying to capture the submit button press of my form and if the form is submitted, the page refreshes and I show a few hidden fields. I would like to capture whether the form has been submitted before or not and if it submitted on reload, I would like to unhide the hidden fields. I was trying to use a global variable to achieve this, however I was unable to make it work properly.
Here is what I tried:
var clicked = false;
$(document).ready(function() {
$("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch'; clicked = true; return true;");
if (clicked == true) {
// show hidden fields
} else {
// don't show hidden fields
}
});
Any suggestions on what is wrong with this code?
As HTTP is stateless, every time you load the page it will use the initial values of whatever you set in JavaScript. You can't set a global variable in JS and simply make that value stay after loading the page again.
There are a couple of ways you could store the value in another place so that you can initialize it on load using JavaScript
Query string
When submitting a form using the GET method, the url gets updated with a query string (?parameter=value&something=42). You can utilize this by setting an input field in the form to a certain value. This would be the simplest example:
<form method="GET">
<input type="hidden" name="clicked" value="true" />
<input type="submit" />
</form>
On initial load of the page, no query string is set. When you submit this form, the name and value combination of the input are passed in the query string as clicked=true. So when the page loads again with that query string you can check if the button was clicked.
To read this data, you can use the following script on page load:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var clicked = getParameterByName('clicked');
(Source)
Ability to use this depends on how your form currently works, if you already use a POST then this could be problematic.
In addition, for larger sets of data this is less than optimal. Passing around a string isn't a big deal but for arrays and objects of data you should probably use Web Storage or cookies. While the details differ a bit across browsers, the practical limit to URI length is around 2000 characters
Web Storage
With the introduction of HTML5 we also got Web Storage, which allows you to save information in the browser across page loads. There is localStorage which can save data for a longer period (as long as the user doesn't manually clear it) and sessionStorage which saves data only during your current browsing session. The latter is useful for you here, because you don't want to keep "clicked" set to true when the user comes back later.
Here I set the storage on the button click event, but you could also bind it to form submit or anything else.
$('input[type="submit"][value="Search"]').click(function() {
sessionStorage.setItem('clicked', 'true');
});
Then when you load the page, you can check if it's set using this:
var clicked = sessionStorage.getItem('clicked');
Even though this value is only saved during this browsing session, it might be possible you want to reset it earlier. To do so, use:
sessionStorage.removeItem('clicked');
If you would want to save a JS object or array you should convert that to a string. According to the spec it should be possible to save other datatypes, but this isn't correctly implemented across browsers yet.
//set
localStorage.setItem('myObject', JSON.stringify(myObject));
//get
var myObject = JSON.parse(localStorage.getItem('myObject'));
Browser support is pretty great so you should be safe to use this unless you need to support really old/obscure browsers. Web Storage is the future.
Cookies
An alternative to Web Storage is saving the data in a cookie. Cookies are mainly made to read data server-side, but can be used for purely client-side data as well.
You already use jQuery, which makes setting cookies quite easy. Again, I use the click event here but could be used anywhere.
$('input[type="submit"][value="Search"]').click(function() {
$.cookie('clicked', 'true', {expires: 1}); // expires in 1 day
});
Then on page load you can read the cookie like this:
var clicked = $.cookie('clicked');
As cookies persist across sessions in your case you will need to unset them as soon as you've done whatever you need to do with it. You wouldn't want the user to come back a day later and still have clicked set to true.
if(clicked === "true") {
//doYourStuff();
$.cookie('clicked', null);
}
(a non-jQuery way to set/read cookies can be found right here)
I personally wouldn't use a cookie for something simple as remembering a clicked state, but if the query string isn't an option and you need to support really old browsers that don't support sessionStorage this will work. You should implement that with a check for sessionStorage first, and only if that fails use the cookie method.
window.name
Although this seems like a hack to me that probably originated from before localStorage/sessionStorage, you could store information in the window.name property:
window.name = "my value"
It can only store strings, so if you want to save an object you'll have to stringify it just like the above localStorage example:
window.name = JSON.stringify({ clicked: true });
The major difference is that this information is retained across not only page refreshes but also different domains. However, it is restricted to the current tab you're in.
This means you could save some information on your page and as long as the user stays in that tab, you could access that same information even if he browsed to another website and back. In general, I would advice against using this unless you need to actually store cross-domain information during a single browsing session.
Try utilizing $.holdReady() , history
function show() {
return $("form input[type=hidden]")
.replaceWith(function(i, el) {
return "<input type=text>"
});
}
$.holdReady(true);
if (history.state !== null && history.state.clicked === true) {
// show hidden fields
// if `history.state.clicked === true` ,
// replace `input type=hidden` with `input type=text`
show();
console.log(history);
} else {
// don't show hidden fields
console.log(history);
}
$.holdReady(false);
$(document).ready(function() {
$("input[type=submit][value=Search]")
.on("click", function(e) {
e.preventDefault();
if (history.state === null) {
// do stuff
history.pushState({"clicked":true});
// replace `input type=hidden` with `input type=text`
show();
console.log(history);
} else {
// do other stuff
};
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST">
<input type="text" name="name" value="" />
<input type="submit" value="Search" />
<input type="hidden" />
<input type="hidden" />
</form>
Using localeStorage or sessionStorage seems to be the best bet.
Intead of saving the clicked variable in the globle scope store it this way:
if(localeStorage.getItem("clicked") === null)
localeStorage.setItem("clicked", "FALSE"); // for the first time
$(document).ready(function() {
$("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch';return true;");
var clicked = localeStorage.getItem("clicked") == "FALSE" ? "TRUE" : "FALSE";
localeStorage.setItem("clicked", clicked);
if (clicked == "TRUE") {
// show hidden fields
} else {
// don't show hidden fields
}
});
You could try this:
$("input[type='submit'][value='Search']").click(function(){
form.act.value='detailSearch';
clicked = true;
return true;
});

Issues accessing localStorage with JavaScript

I'm trying to run a function when body loads, that will check if the user is logged in, and if not redirect them to the login page. Here is the login function :
function login() {
var mail = document.getElementById('mail').value; //get values
var psw = document.getElementById('psw').value; //get values
localStorage.setItem('logged_in', true); //specify that user is logged in
localStorage.setItem('mail', mail); //store mail
window.location.replace('pages/home.html'); //redirect to home page
}
And the function to check if the user is logged in :
function check_logged_in() {
const logged_in = localStorage.getItem('logged_in');
if (logged_in == null) { //check if user is logged in
alert('You are not logged in, you are about to be redirected. '); //alert user
window.location.replace("../index.html"); //redirect to login page
}
}
The problem is that even if the login function run before, I am redirected. I think that the localStorage resets on each redirection. If that is the problem, do you know the way to prevent this, or if it isn't the problem, do you know what it might be?
Based on the documentation a localStorage item can either be null (when it's empty) or a string. It does not store any other data types.
The expression
localStorage.setItem("logged_in", true);
Does not save a boolean value to the localStorage item. instead, it saves the string value "true"

How to store an event that was clicked and automatically display in jQuery? [duplicate]

I am trying to capture the submit button press of my form and if the form is submitted, the page refreshes and I show a few hidden fields. I would like to capture whether the form has been submitted before or not and if it submitted on reload, I would like to unhide the hidden fields. I was trying to use a global variable to achieve this, however I was unable to make it work properly.
Here is what I tried:
var clicked = false;
$(document).ready(function() {
$("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch'; clicked = true; return true;");
if (clicked == true) {
// show hidden fields
} else {
// don't show hidden fields
}
});
Any suggestions on what is wrong with this code?
As HTTP is stateless, every time you load the page it will use the initial values of whatever you set in JavaScript. You can't set a global variable in JS and simply make that value stay after loading the page again.
There are a couple of ways you could store the value in another place so that you can initialize it on load using JavaScript
Query string
When submitting a form using the GET method, the url gets updated with a query string (?parameter=value&something=42). You can utilize this by setting an input field in the form to a certain value. This would be the simplest example:
<form method="GET">
<input type="hidden" name="clicked" value="true" />
<input type="submit" />
</form>
On initial load of the page, no query string is set. When you submit this form, the name and value combination of the input are passed in the query string as clicked=true. So when the page loads again with that query string you can check if the button was clicked.
To read this data, you can use the following script on page load:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var clicked = getParameterByName('clicked');
(Source)
Ability to use this depends on how your form currently works, if you already use a POST then this could be problematic.
In addition, for larger sets of data this is less than optimal. Passing around a string isn't a big deal but for arrays and objects of data you should probably use Web Storage or cookies. While the details differ a bit across browsers, the practical limit to URI length is around 2000 characters
Web Storage
With the introduction of HTML5 we also got Web Storage, which allows you to save information in the browser across page loads. There is localStorage which can save data for a longer period (as long as the user doesn't manually clear it) and sessionStorage which saves data only during your current browsing session. The latter is useful for you here, because you don't want to keep "clicked" set to true when the user comes back later.
Here I set the storage on the button click event, but you could also bind it to form submit or anything else.
$('input[type="submit"][value="Search"]').click(function() {
sessionStorage.setItem('clicked', 'true');
});
Then when you load the page, you can check if it's set using this:
var clicked = sessionStorage.getItem('clicked');
Even though this value is only saved during this browsing session, it might be possible you want to reset it earlier. To do so, use:
sessionStorage.removeItem('clicked');
If you would want to save a JS object or array you should convert that to a string. According to the spec it should be possible to save other datatypes, but this isn't correctly implemented across browsers yet.
//set
localStorage.setItem('myObject', JSON.stringify(myObject));
//get
var myObject = JSON.parse(localStorage.getItem('myObject'));
Browser support is pretty great so you should be safe to use this unless you need to support really old/obscure browsers. Web Storage is the future.
Cookies
An alternative to Web Storage is saving the data in a cookie. Cookies are mainly made to read data server-side, but can be used for purely client-side data as well.
You already use jQuery, which makes setting cookies quite easy. Again, I use the click event here but could be used anywhere.
$('input[type="submit"][value="Search"]').click(function() {
$.cookie('clicked', 'true', {expires: 1}); // expires in 1 day
});
Then on page load you can read the cookie like this:
var clicked = $.cookie('clicked');
As cookies persist across sessions in your case you will need to unset them as soon as you've done whatever you need to do with it. You wouldn't want the user to come back a day later and still have clicked set to true.
if(clicked === "true") {
//doYourStuff();
$.cookie('clicked', null);
}
(a non-jQuery way to set/read cookies can be found right here)
I personally wouldn't use a cookie for something simple as remembering a clicked state, but if the query string isn't an option and you need to support really old browsers that don't support sessionStorage this will work. You should implement that with a check for sessionStorage first, and only if that fails use the cookie method.
window.name
Although this seems like a hack to me that probably originated from before localStorage/sessionStorage, you could store information in the window.name property:
window.name = "my value"
It can only store strings, so if you want to save an object you'll have to stringify it just like the above localStorage example:
window.name = JSON.stringify({ clicked: true });
The major difference is that this information is retained across not only page refreshes but also different domains. However, it is restricted to the current tab you're in.
This means you could save some information on your page and as long as the user stays in that tab, you could access that same information even if he browsed to another website and back. In general, I would advice against using this unless you need to actually store cross-domain information during a single browsing session.
Try utilizing $.holdReady() , history
function show() {
return $("form input[type=hidden]")
.replaceWith(function(i, el) {
return "<input type=text>"
});
}
$.holdReady(true);
if (history.state !== null && history.state.clicked === true) {
// show hidden fields
// if `history.state.clicked === true` ,
// replace `input type=hidden` with `input type=text`
show();
console.log(history);
} else {
// don't show hidden fields
console.log(history);
}
$.holdReady(false);
$(document).ready(function() {
$("input[type=submit][value=Search]")
.on("click", function(e) {
e.preventDefault();
if (history.state === null) {
// do stuff
history.pushState({"clicked":true});
// replace `input type=hidden` with `input type=text`
show();
console.log(history);
} else {
// do other stuff
};
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST">
<input type="text" name="name" value="" />
<input type="submit" value="Search" />
<input type="hidden" />
<input type="hidden" />
</form>
Using localeStorage or sessionStorage seems to be the best bet.
Intead of saving the clicked variable in the globle scope store it this way:
if(localeStorage.getItem("clicked") === null)
localeStorage.setItem("clicked", "FALSE"); // for the first time
$(document).ready(function() {
$("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch';return true;");
var clicked = localeStorage.getItem("clicked") == "FALSE" ? "TRUE" : "FALSE";
localeStorage.setItem("clicked", clicked);
if (clicked == "TRUE") {
// show hidden fields
} else {
// don't show hidden fields
}
});
You could try this:
$("input[type='submit'][value='Search']").click(function(){
form.act.value='detailSearch';
clicked = true;
return true;
});

Retain img src on page reload [duplicate]

I am trying to capture the submit button press of my form and if the form is submitted, the page refreshes and I show a few hidden fields. I would like to capture whether the form has been submitted before or not and if it submitted on reload, I would like to unhide the hidden fields. I was trying to use a global variable to achieve this, however I was unable to make it work properly.
Here is what I tried:
var clicked = false;
$(document).ready(function() {
$("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch'; clicked = true; return true;");
if (clicked == true) {
// show hidden fields
} else {
// don't show hidden fields
}
});
Any suggestions on what is wrong with this code?
As HTTP is stateless, every time you load the page it will use the initial values of whatever you set in JavaScript. You can't set a global variable in JS and simply make that value stay after loading the page again.
There are a couple of ways you could store the value in another place so that you can initialize it on load using JavaScript
Query string
When submitting a form using the GET method, the url gets updated with a query string (?parameter=value&something=42). You can utilize this by setting an input field in the form to a certain value. This would be the simplest example:
<form method="GET">
<input type="hidden" name="clicked" value="true" />
<input type="submit" />
</form>
On initial load of the page, no query string is set. When you submit this form, the name and value combination of the input are passed in the query string as clicked=true. So when the page loads again with that query string you can check if the button was clicked.
To read this data, you can use the following script on page load:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var clicked = getParameterByName('clicked');
(Source)
Ability to use this depends on how your form currently works, if you already use a POST then this could be problematic.
In addition, for larger sets of data this is less than optimal. Passing around a string isn't a big deal but for arrays and objects of data you should probably use Web Storage or cookies. While the details differ a bit across browsers, the practical limit to URI length is around 2000 characters
Web Storage
With the introduction of HTML5 we also got Web Storage, which allows you to save information in the browser across page loads. There is localStorage which can save data for a longer period (as long as the user doesn't manually clear it) and sessionStorage which saves data only during your current browsing session. The latter is useful for you here, because you don't want to keep "clicked" set to true when the user comes back later.
Here I set the storage on the button click event, but you could also bind it to form submit or anything else.
$('input[type="submit"][value="Search"]').click(function() {
sessionStorage.setItem('clicked', 'true');
});
Then when you load the page, you can check if it's set using this:
var clicked = sessionStorage.getItem('clicked');
Even though this value is only saved during this browsing session, it might be possible you want to reset it earlier. To do so, use:
sessionStorage.removeItem('clicked');
If you would want to save a JS object or array you should convert that to a string. According to the spec it should be possible to save other datatypes, but this isn't correctly implemented across browsers yet.
//set
localStorage.setItem('myObject', JSON.stringify(myObject));
//get
var myObject = JSON.parse(localStorage.getItem('myObject'));
Browser support is pretty great so you should be safe to use this unless you need to support really old/obscure browsers. Web Storage is the future.
Cookies
An alternative to Web Storage is saving the data in a cookie. Cookies are mainly made to read data server-side, but can be used for purely client-side data as well.
You already use jQuery, which makes setting cookies quite easy. Again, I use the click event here but could be used anywhere.
$('input[type="submit"][value="Search"]').click(function() {
$.cookie('clicked', 'true', {expires: 1}); // expires in 1 day
});
Then on page load you can read the cookie like this:
var clicked = $.cookie('clicked');
As cookies persist across sessions in your case you will need to unset them as soon as you've done whatever you need to do with it. You wouldn't want the user to come back a day later and still have clicked set to true.
if(clicked === "true") {
//doYourStuff();
$.cookie('clicked', null);
}
(a non-jQuery way to set/read cookies can be found right here)
I personally wouldn't use a cookie for something simple as remembering a clicked state, but if the query string isn't an option and you need to support really old browsers that don't support sessionStorage this will work. You should implement that with a check for sessionStorage first, and only if that fails use the cookie method.
window.name
Although this seems like a hack to me that probably originated from before localStorage/sessionStorage, you could store information in the window.name property:
window.name = "my value"
It can only store strings, so if you want to save an object you'll have to stringify it just like the above localStorage example:
window.name = JSON.stringify({ clicked: true });
The major difference is that this information is retained across not only page refreshes but also different domains. However, it is restricted to the current tab you're in.
This means you could save some information on your page and as long as the user stays in that tab, you could access that same information even if he browsed to another website and back. In general, I would advice against using this unless you need to actually store cross-domain information during a single browsing session.
Try utilizing $.holdReady() , history
function show() {
return $("form input[type=hidden]")
.replaceWith(function(i, el) {
return "<input type=text>"
});
}
$.holdReady(true);
if (history.state !== null && history.state.clicked === true) {
// show hidden fields
// if `history.state.clicked === true` ,
// replace `input type=hidden` with `input type=text`
show();
console.log(history);
} else {
// don't show hidden fields
console.log(history);
}
$.holdReady(false);
$(document).ready(function() {
$("input[type=submit][value=Search]")
.on("click", function(e) {
e.preventDefault();
if (history.state === null) {
// do stuff
history.pushState({"clicked":true});
// replace `input type=hidden` with `input type=text`
show();
console.log(history);
} else {
// do other stuff
};
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST">
<input type="text" name="name" value="" />
<input type="submit" value="Search" />
<input type="hidden" />
<input type="hidden" />
</form>
Using localeStorage or sessionStorage seems to be the best bet.
Intead of saving the clicked variable in the globle scope store it this way:
if(localeStorage.getItem("clicked") === null)
localeStorage.setItem("clicked", "FALSE"); // for the first time
$(document).ready(function() {
$("input[type='submit'][value='Search']").attr("onclick", "form.act.value='detailSearch';return true;");
var clicked = localeStorage.getItem("clicked") == "FALSE" ? "TRUE" : "FALSE";
localeStorage.setItem("clicked", clicked);
if (clicked == "TRUE") {
// show hidden fields
} else {
// don't show hidden fields
}
});
You could try this:
$("input[type='submit'][value='Search']").click(function(){
form.act.value='detailSearch';
clicked = true;
return true;
});

localStorage for phonegap will store stuff after exiting application?

How can I use localStorage to store login credentials for my application? I'm thinking it will store it somewhere when I exit the app, and then when I open the application again the fields will be prefilled with the information from localStorage. Here is my code so far.
function onDeviceReady() {
alert("ready");
var email = window.localStorage.getItem("email");
var password = window.localStorage.getItem("password");
document.getElementById("email").value = email;
document.getElementById("password").value = password;
}
//If checkbox gets checked then save credentials, if unchecked then forget
function rememberMe() {
if(document.getElementById('remember_me').checked) {
alert("checked");
window.localStorage.setItem("email", document.getElementById("email").value);
window.localStorage.setItem("password", docuement.getElementById("password").value);
}
else {
alert("unchecked");
window.localstorage.clear();
}
}
Best way to do it is use webSQL or SQLite database. save credentials when anybody tries to login and then when someone opens the app, fill the boxes by reading data from database on pageload or device ready function.
localStorage can hold object´s data until it gets removed from the same, but sessionStorage will clear the data when you close the tab/browser.

Categories

Resources