Jump to content

Question regarding ajax login setting a $_COOKIE[] value


maxxd
Go to solution Solved by maxxd,

Recommended Posts

Hi y'all. It's been forever and a day since I've dealt with cookies, and I can't get through the cobwebs in my brain about them. I know that cookies have to be set before any output goes to the browser, but if I'm not mistaken, it's the same with sessions and sessions work in this situation. Unfortunately, the client needs cookies for integration with an existing piece of software.

 

Basically, what's happening is this: You load a page, click the 'login' button, which uses JQuery to change the display on the login screen from 'none' to 'block'. Use the newly-visible login form to enter username and password, which are passed via ajax to my login function. If the login is successful, I set the cookie variable and redirect the user to the protected page. However, despite the ajax reporting a successful login and redirecting the browser as expected, the check on the protected page is kicking the user back to the beginning because the cookie was never actually set.

 

FunctionsClass.php:

/**
 *	Logs in the requesting user with the agent and email values supplied via AJAX.
 *	@return		string					JSON-encoded array
 */
	public function agentLogin(){
		$ret['success'] = $this->_site->login($_POST['username'],$_POST['password']);
		$ret['location'] = '/protected-page';
 		print(json_encode($ret));
 		die();
	 }

Site.php (that's $_site in FunctionsClass):

/**
 *	Logs in the agent.
 *	Checks to see if the user is already logged in, if not, attempts to do so.
 *	@param		string		$un				username
 *	@param		string		$pw				password
 *	@return		boolean
 */
	public function logIn($un, $pw){
		if($this->isLoggedIn()){
			return true;
		}
		return $this->logAgentIn($un,$pw);
	}

/**
 *	Check to see if the cookie set so we know if the user has logged in.
 *	@return		boolean
 */
	public function isLoggedIn(){
//		return !empty($_SESSION['mycheckvariable']);
		return !empty($_COOKIE['mycheckvariable']);
	}

/**
 *	Log the user in.
 *	@param		string		$un				username
 *	@param		string		$pw				password
 *	@return		boolean
 */
	private function logAgentIn($un,$pw){
//		$_SESSION['mycheckvariable']['email'] = 'me@notmyemail.com';
		setcookie('mycheckvariable','me@notmyrealemail.com',time()+60*60*8,'/');
		return true;
	}

It's not as though I'm even actually checking a database - just trying to stub this out for client presentation. And, if I uncomment the two lines using sessions and comment out the cookies, it all works perfectly. I'm not at all sure what I'm missing and would very much appreciate some other eyes on this - any takers?

 

I'm using WordPress, if that matters at all...

 

Thanks in advance!

Link to comment
Share on other sites

The browser is forwarded to a target page upon successful login - that's where I'm checking to make sure the cookies are set. Sorry - that's in the JavaScript that I totally forgot to post.

$('#login-popup #submit').click(function(e){
	e.preventDefault();
	$.ajax({
		type:'post',
		url:myVar.ajaxUrl,
		data:{
			'action':'agent_login',
			'username':$('#login-popup #username').val(),
			'password':$('#login-popup #password').val()
		},
	}).done(function(ajaxObject){
		var resp = JSON.parse(ajaxObject);
		if(resp.success == true){
			clearLogin();
			window.location.replace(resp.location);
		}
	});
});
Edited by maxxd
Link to comment
Share on other sites

Check the AJAX response headers to see if the cookie was actually set. If not, and you're sure that the setcookie() was executed (code is simple enough to be sure it was) then there may have been output at some point preventing the cookie from being set. Check your error log for any indication of that.

Link to comment
Share on other sites

I've only been working with WordPress for about two months, so I'm not sure what it's running in addition to the admin_ajax_* hook, but the output in the console shows only the expected JSON, which is output after the cookies are meant to be set. And wouldn't the session version also fail if there was output prior to the setting of the variables? I hadn't thought about checking the error log (duh) so thank you for the reminder!

Link to comment
Share on other sites

You didn't say you were coding underneath WP.  Not nice.  You should be posting in the CMS forum.

I did mention it at the end of my original post, but I can imagine skimming by it and I probably should have called it out more. I didn't post in the CMS forum or make more of a deal about the WP usage because I kinda figured it was just me having not used cookies in years and forgetting things as opposed to something WP is injecting or doing behind the scenes. If it's in the wrong forum and a moderator happens to be reading this, any chance you could move it over to the proper location?

 

Is that two return statements in isLoggedIn? The second one will never be executed.

The first is commented out and won't be run in this scenario. (It is being run in dev because it actually works.) I just left it there because it's identical and does work...

 

I gotta Google it, but am I wrong in my recollection that session variables can't be set after output goes to the browser, same as cookies?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.