I load a javascript at the end of my html page with a function loginsucces(), which should be executed after a successfull login redirect to the page. It works perfectly in default browser mode(chrome), however when i load the page in incognito mode, it executes the function while the page is loaded the first time. Due to this behavior i got syntax errors because the php variables are not initialized yet. I know i can get around that somehow but i am curios to know why is the js function is executed in incognito mode while first-time page load and how can i avoid this?
<script>
function loginsuccess(){
if(!<?php echo isAuth() ?>){ return; }
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var json = JSON.parse(xhr.responseText);
...
}
}
xhr.open("GET","http://myurl.com/api/users/"+<?php echo currentUserId()?>,true);
xhr.send();
}
</script>
You should perhaps do this instead.
<script>
<?php if (isAuth()): ?>
function loginsuccess(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var json = JSON.parse(xhr.responseText);
...
}
}
xhr.open("GET","http://myurl.com/api/users/"+<?php echo currentUserId()?>,true);
xhr.send();
}
<?php endif ?>
</script>
Alternatively to keep things separate and allow you to move the code out later on, instead of it being inline, is to define the state beforehand in a global var.
This could be put in the head
of the document.
<?php if (isAuth()): ?>
<script>
var user = {
loggedIn: true,
userId: <?php echo currentUserId()?>
};
</script>
<?php endif ?>
Now you don't have PHP vars in your js which will allow you to move it out into a .js file if you wanted.
<script>
function loginsuccess() {
if (typeof user === "undefined" || user.loggedIn !== true) {
return
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200){
var json = JSON.parse(xhr.responseText);
...
}
}
xhr.open("GET","http://myurl.com/api/users/"+user.userId,true);
xhr.send();
}
</script>