Right way to verify that a user is logged - javascript

I use AJAX requests to make the user area of my website.
A "Log off" button must be displayed only when the user is connected.
For connecting a user, here my AJAX request:
function requestSI() {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
document.getElementById("popup_login").innerHTML = "<img src='img/index/cross.png' id='close' onclick ='hidelogin()' /><div id='color2'></div><h2 id=login_title>";
document.getElementById("popup_login").innerHTML += this.responseText;
if (isUserLogged()){
var x = document.getElementById("log_off");
x.classList.remove("inative_logoff");
x.classList.add("active_logoff");
}
}
};
var login_fieldSI = encodeURIComponent(document.getElementById("login_fieldSI").value);
var password_fieldSI = encodeURIComponent(document.getElementById("password_fieldSI").value);
xhr.open("POST", "php/login.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("Login_fieldSI="+login_fieldSI+"&Password_fieldSI="+password_fieldSI);
}
And here my AJAX request to check if a user is connected:
function isUserLogged(){
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
alert(this.responseText);
if (this.responseText == "true") return true;
else return false;
}
};
xhr.open("POST", "php/is_user_connected.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(null);
}
My "Log off" button doesn't display for some reason.

function requestSI() {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
document.getElementById("popup_login").innerHTML = "<img src='img/index/cross.png' id='close' onclick ='hidelogin()' /><div id='color2'></div><h2 id=login_title>";
document.getElementById("popup_login").innerHTML += this.responseText;
isUserLogged();
}
};
var login_fieldSI = encodeURIComponent(document.getElementById("login_fieldSI").value);
var password_fieldSI = encodeURIComponent(document.getElementById("password_fieldSI").value);
xhr.open("POST", "php/login.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("Login_fieldSI="+login_fieldSI+"&Password_fieldSI="+password_fieldSI);
}
----------
function isUserLogged(){
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
alert(this.responseText);
if (this.responseText == "true"){
alert("ok");
alert("test function");
var x = document.getElementById("log_off");
x.classList.remove("inative_logoff");
x.classList.add("active_logoff");
}
else {
//do your other code..
}
}
};
xhr.open("POST", "php/is_user_connected.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(null);
}

You can try if (isUserLogged() == true){ instead if (isUserLogged()){

Related

Run a script from a link

I have the following script that shows me information in a div, it works very well but with a button ... I am trying to make it walk from a link, I tried many ways and nothing, any ideas?
<script>
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementById("contenido").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("contenido").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
history.pushState(null, "", str+ ".xhttp");
xhttp.send();
}
</script>
<input type='button' value='6df67913c1' onclick='showCustomer(this.value);' />
You have to do something like this
const myLinkButton = document.getElementById('my-Link-button')
;
myLinkButton.onclick=e=>
{
e.preventDefault() // -> disable link action for new url
console.log( myLinkButton.dataset.value )
}
<a href="#" data-value="6df67913c1" id="my-Link-button" >button by link</a>
Use <a href="JavaScript: void (0)" onclick="callYourFunction()>link<\a>
You can do this.
<script>
function showCustomer(element) {
const str = element.getAttribute('data-value')
var xhttp;
if (str == "") {
document.getElementById("contenido").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("contenido").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
history.pushState(null, "", str+ ".xhttp");
xhttp.send();
}
</script>
Same, from link

How Do not call function except storage the script in local storage completed?

I do not want to call function LoadLocal(); unless the task window.localStorage.setItem( 'scriptjs', Base64.encode(xmlhttp.responseText) );
really has been completed. How?
function loadServer() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
window.localStorage.setItem( 'scriptjs', Base64.encode(xmlhttp.responseText) );
loadLocal();
}
else if (xmlhttp.status == 400) {
loadLocal();
}
else {
loadLocal();
}
}
};
xmlhttp.open("GET", "http://tokojs.com/app/hokinawafashion.js?"+Math.random(), true);
xmlhttp.send();
}
I do not want to call function LoadLocal(); unless the task window.localStorage.setItem( 'scriptjs', Base64.encode(xmlhttp.responseText) );
has been completed. How?
This is full script
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(r){var t,e,o,a,h,n,c,d="",C=0;for(r=Base64._utf8_encode(r);C<r.length;)t=r.charCodeAt(C++),e=r.charCodeAt(C++),o=r.charCodeAt(C++),a=t>>2,h=(3&t)<<4|e>>4,n=(15&e)<<2|o>>6,c=63&o,isNaN(e)?n=c=64:isNaN(o)&&(c=64),d=d+this._keyStr.charAt(a)+this._keyStr.charAt(h)+this._keyStr.charAt(n)+this._keyStr.charAt(c);return d},decode:function(r){var t,e,o,a,h,n,c,d="",C=0;for(r=r.replace(/[^A-Za-z0-9\+\/\=]/g,"");C<r.length;)a=this._keyStr.indexOf(r.charAt(C++)),h=this._keyStr.indexOf(r.charAt(C++)),n=this._keyStr.indexOf(r.charAt(C++)),c=this._keyStr.indexOf(r.charAt(C++)),t=a<<2|h>>4,e=(15&h)<<4|n>>2,o=(3&n)<<6|c,d+=String.fromCharCode(t),64!=n&&(d+=String.fromCharCode(e)),64!=c&&(d+=String.fromCharCode(o));return d=Base64._utf8_decode(d)},_utf8_encode:function(r){r=r.replace(/\r\n/g,"\n");for(var t="",e=0;e<r.length;e++){var o=r.charCodeAt(e);o<128?t+=String.fromCharCode(o):o>127&&o<2048?(t+=String.fromCharCode(o>>6|192),t+=String.fromCharCode(63&o|128)):(t+=String.fromCharCode(o>>12|224),t+=String.fromCharCode(o>>6&63|128),t+=String.fromCharCode(63&o|128))}return t},_utf8_decode:function(r){for(var t="",e=0,o=c1=c2=0;e<r.length;)o=r.charCodeAt(e),o<128?(t+=String.fromCharCode(o),e++):o>191&&o<224?(c2=r.charCodeAt(e+1),t+=String.fromCharCode((31&o)<<6|63&c2),e+=2):(c2=r.charCodeAt(e+1),c3=r.charCodeAt(e+2),t+=String.fromCharCode((15&o)<<12|(63&c2)<<6|63&c3),e+=3);return t}}
var versi = '1';
// Load Script Local
var sc = localStorage.getItem('scriptjs');
function loadLocal(){
if (sc === undefined || sc === null || sc.length === 0){
loadServer();
}
else{
var s = document.createElement('script');
s.type = 'text/javascript';
var code = Base64.decode(sc);
try {
s.appendChild(document.createTextNode(code));
document.body.appendChild(s);
} catch (e) {
s.text = code;
document.body.appendChild(s);
}
}
}
//
// Load Script Server
function loadServer() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
window.localStorage.setItem( 'scriptjs', Base64.encode(xmlhttp.responseText) );
loadLocal();
}
else if (xmlhttp.status == 400) {
loadLocal();
}
else {
loadLocal();
}
}
};
xmlhttp.open("GET", "http://tokojs.com/app/hokinawafashion.js?"+Math.random(), true);
xmlhttp.send();
}
//
window.onload = loadServer();

JavaScript var outside function

How do I retrieve returndata variable outside fn() function?
function fn() {
var xmlhttp = new XMLHttpRequest();
var vars = "request=something";
xmlhttp.open("POST", "script.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var returndata = xmlhttp.responseText;
}
}
xmlhttp.send(vars);
}
You need to define global variable before function and then store the result into this variable. The way you do it now, is definition of local variable.
var returndata;
function fn() {
var xmlhttp = new XMLHttpRequest();
var vars = "request=something";
xmlhttp.open("POST", "script.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
returndata = xmlhttp.responseText;
}
}
xmlhttp.send(vars);
}
AJAX requests are asynchronous. You cannot have the pizza before it is baked. In real life you call the pizza company. They bake it and you wait. AJAX is the same. So setting the returndata won't do it all by itself.
function fn() {
var xmlhttp = new XMLHttpRequest();
var vars = "request=something";
xmlhttp.open("POST", "script.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var returndata = xmlhttp.responseText;
}
}
xmlhttp.send(vars);
}
The readystate function isn't there for nothing. It waits until the request has been processed. From there on you can go on. Every function/script that is depended on the returned data should be called upon from that function.
Still you can do this:
var returndata; //this will now be a global variable.
function fn() {
var xmlhttp = new XMLHttpRequest();
var vars = "request=something";
xmlhttp.open("POST", "script.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var returndata = xmlhttp.responseText;
doSomeThing(); //fire depended value.
}
}
xmlhttp.send(vars);
}
function doSomething()
{
if(returndata)
{
//do Something
}
else
{
alert("Data isn't loaded yet");
}
}

XMLhttprequest issues

I'm trying to work on xmlhttprequests which isn't working. When inserting an alert box I receive a status of 0. Cant quite figure out what's wrong.
function submitChat() {
if (form1.uname.value != '' && form1.msg.value != '') {
var uname = form1.uname.value;
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
alert(xmlhttp.status);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "insert.php?uname=" + uname + "&msg=" + msg, true);
xmlhttp.send();
} else {
alert("All Fields are Mandatory !!!");
return;
}
}
<form name="form1" action="#">`` Chatname:
<input type="text" name="uname" />
<br/>
<textarea name="msg"></textarea>
Send
<br/>
<br/>
</form>
<div id="chatlogs">
Loading Chat History !!!!!!!!!!
</div>
You should do .open() before your alert. So your code becomes like this:
function submitChat() {
if (form1.uname.value != '' && form1.msg.value != '') {
var uname = form1.uname.value;
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","insert.php?uname="+uname+"&msg="+msg,true);
alert (xmlhttp.status);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readystate==4 && xmlhttp.status==200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
} else {
alert("All Fields are Mandatory !!!");
return;
}
}

Function call after AJAX request does not work in javascript

I have a function where the alert is working:
function RequestNext() {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
MyCard = GetCard(xhr.responseText);
**alert(MyCard.GetNo());**
return MyCard;
}
};
xhr.open("GET", "../../HttpRequest_Next.php" , true);
xhr.send(null);
}
Then I have this other function where the first one gets called and the same alert does not work:
function Start(){
var MyCard = RequestNext();
alert("Patience.js");
**alert(MyCard.GetNo());**
alert("test2");
//alert(Card.GetKind());
//WriteCard(Card);
alert("test3");
}
For information, those functions are in 2 files.
This is where a callback is a great idea. Basically you pass a function as an argument, so that you can then run that function when the ajax (which is asyncronous) completes. The syntax here may be slightly off, but you could do something like:
function RequestNext(callback) {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
MyCard = GetCard(xhr.responseText);
**alert(MyCard.GetNo());**
if (typeof callback=='undefined') return MyCard;
else {
return callback.call(MyCard);
}
}
};
xhr.open("GET", "../../HttpRequest_Next.php" , true);
xhr.send(null);
}
function Start(){
var MyCard = RequestNext(function() {
alert("Patience.js");
alert(this.GetNo());
alert("test2");
//alert(this.GetKind());
//WriteCard(this);
alert("test3");
return this;
});
}

Categories