Jump to content

Hiding and showing html elements with JavaScript when a user logs in and starts a PHP session


ArgusPMC

Recommended Posts

I have a dilemma here. I'm using AJAX to send and retrieve data from PHP. My login scripts function this way, they extract some data from a couple of inputs, send it to PHP to check with the database and then send it back to JavaScript to display some information based on those results. What I would do is that I would hide or unhide, elements if the returned information indicated that the login process was succesful. But then this doesn't work with other pages, it just resets everything. I found some ways to check, but I don't necessarily like them, the first one was to do something like this:

var session = '<?php echo $_SESSION['name']?>'

This doesn't work for me because it doesn't adhere to MVC, it also means I need to change the extension file to get the contents, It's just not right to do something like that. Otherwise, I could just embed PHP into my HTML and display the information like that, but I'd like to remain consistent in how I collect information and I already chose to use AJAX and not the usual form method. I could always just create a small script to check, hide and unhide whatever's necessary but then the PHP file to get that would be a waste of space and time, especially if all its going to do is to send $_SESSION contents. I've already got my login script in JavaScript, I'd like to think I could handle it from there. Then they also tell me I could just handle it from cookies, but what if the user disables them?

 

In any case this is what my javascript code looks like:

/* Code to extract login details from main page. An event listener is added to the button used to submit a user's details. AFter that, said information is sent to an external php file which is used to check if a user exists and start a session*/window.onload = function findLoginButton() {    var button = document.getElementById("start_session").addEventListener("click", sendUserDetails);    	/*Unobtrusive javascript listener, added to button */	}function sendUserDetails(){	var xmlhttp;	var username;	var password;	var joinButton;	var loginButton;	var logoutButton;	var dataToSend = [];	var JSONdataToSend;		  if (window.XMLHttpRequest){	  xmlhttp = new XMLHttpRequest();        /* Used for IE7+,FireFox, Opera, Chrome, Safari */  } else if (window.ActiveXObject) {	  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");   /* Compatibility for IE6 browsers */  } else {	  throw new Error("Your browser is not compatible with XMLHTTP");	  return false;  }    loginButton = document.getElementById("login");  joinButton = document.getElementById("join");  logoutButton = document.getElementById("logout");  username = document.getElementById("login_username");  password = document.getElementById("login_password");    console.log(loginButton);  console.log(joinButton);  if (username.value == ""  || password.value == "" ){	  alert("Please, fill out all fields before submitting");	  return false;  }    dataToSend[0] = username.value;  dataToSend[1] = password.value;  JSONdataToSend = JSON.stringify({dataToSend: dataToSend});    xmlhttp.onreadystatechange=function()	  {		  if (xmlhttp.readyState==4 && xmlhttp.status==200){				serverResponse = xmlhttp.responseText				console.log(serverResponse);				var code = parseInt(serverResponse);				console.log(code);				if(code == 2){					alert("Admin login succesful.")					username.value = "";					loginButton.style.display = "none";					joinButton.style.display = "none";					logoutButton.style.display = "block";					window.location = "register.php";				} else if(code == 1) {					username.value = "";					loginButton.style.display = "none";					joinButton.style.display = "none";					logoutButton.style.display = "block";					alert("Login succesful.");					window.location = "register.php";				} else {					alert("The username or password that you have entered is invalid or it doesn't exist. Please try again, or create an account.");					username.value = "";					password.value = "";					return false;				}		  }	  }	 	xmlhttp.open("POST","php/checkUserExistence.php", true);	xmlhttp.setRequestHeader("Content-type","application/json;charset=UTF-8");	xmlhttp.send(JSONdataToSend);}

If anyone can help me it'd be great, if there is no other way but to embed PHP to html, then I guess I will do that, but I don't exactly like it either, since that is the sort of thing that also doesn't adhere to MVC.

Link to comment
Share on other sites

If you're trying to do something like hide a login form if they are already logged in when the page loads, then that logic is handled with PHP to simply not output those HTML elements if the session indicates that they are logged in. It seems kludgy to send the whole page to Javascript and then use Javascript to hide things that they shouldn't see. If they shouldn't see those things then don't send them in the first place, that's PHP.

Link to comment
Share on other sites

  • 1 month later...

Sorry that I didn't answer this sooner, but I figured it out a while a go. Apparently it wasn't even that difficult to begin with. Whether it is correct or not I don't know, but it saves me a lot of extra buttons that I may have had to put into the html. I don't know if what I'm doing is preferable than to what is done normally. By this I mean, I try to keep PHP and JavaScript off my HTML as much as it is possible. So far it has been way more organized and clean than just combining all three into the same thing. I don't really know if that is the correct way to do it, but that's how I do it.

 

However, thank you for the advice, I shall take it into consideration with my next project.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...