jQuery Login w/No Page Refresh

I’m trying to achive a no page refresh with a login script, I just don’t know where to get started…

I’ve attached my loging script and login form, I know how to include jquery into the page but how do I achive a login without a page refresh for my script?

<?php

if($_POST['submit']=='Login')
{
	// Checking whether the Login form has been submitted
	
	$err = array();
	// Will hold our errors
	
	
	if(!$_POST['username'] || !$_POST['password'])
		$err[] = 'All the fields must be filled in!';
	
	if(!count($err))
	{
		$_POST['username'] = mysql_real_escape_string($_POST['username']);
		$_POST['password'] = mysql_real_escape_string($_POST['password']);
		$_POST['rememberMe'] = (int)$_POST['rememberMe'];
		
		// Escaping all input data

		$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM members WHERE usr='{$_POST['username']}' AND pass='{$_POST['password']}'"));

		if($row['usr'])
		{
			// If everything is OK login
			
			$_SESSION['usr']=$row['usr'];
			$_SESSION['id'] = $row['id'];
			$_SESSION['rememberMe'] = $_POST['rememberMe'];
			
			// Store some data in the session
			
			setcookie('Remember',$_POST['rememberMe']);
		}
		else $err[]='Wrong username and/or password!';
	}
	
	if($err)
	$_SESSION['msg']['login-err'] = implode('<br />',$err);
	// Save the error messages in the session

	header("Location: index.php");
	exit;
}


?>

				<form class="clearfix" action="" method="post">
					<h1>Member Login</h1>
                    
                    <?php
						
						if($_SESSION['msg']['login-err'])
						{
							echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
							unset($_SESSION['msg']['login-err']);
						}
					?>
					
					<label class="error" for="username" id="username_error">Username:</label>
					<input class="text-input" type="text" name="username" id="username" value="" size="23" />	
      				
					<label class="error grey" id="password_error" for="password">Password:</label>
					<input class="field" type="password" name="password" id="password" size="23" />
	            	<label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" /> &nbsp;Remember me</label>
        			
        			<div class="clear"></div>
					      <input type="submit" name="submit" class="button" id="Login" value="Login" />

				</form>

Google has the answer

the only way I can think of is with AJAX, with or without a [URL=“http://css-tricks.com/modal-login-pages/”]modal window.

but apart from the security weaknesses, are you sure you want to do it this way because users with javascript disabled in their browsers won’t be able to log in with this method

I’ve actually kind of figured it out for the login part, but I want to implement the same feature for my user registration but just can’t seem to get it working.

The code is this for register:

<?php
session_name('movie');
session_start();

//Connect to database from here
$link = mysql_connect('localhost', 'root', 'root'); 
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
//select the database | Change the name of database from here
mysql_select_db('loginform'); 

		$_POST['email'] = mysql_real_escape_string($_POST['email']);
		$username = $_POST['username'] = mysql_real_escape_string($_POST['username']);
		$password = $_POST['password'] = mysql_real_escape_string($_POST['password']);

		// Escape the input data
		
		
		mysql_query("	INSERT INTO tz_members(fname, lname, usr, pass, email, regIP, dt)
						VALUES(
						
							'".$_POST['fname']."',
							'".$_POST['lname']."',
							'".$_POST['username']."',
							'".$_POST['password']."',
							'".$_POST['email']."',
							'".$_SERVER['REMOTE_ADDR']."',
							NOW()
							
						)");
		
		if(mysql_affected_rows($link)==1)
		{
			send_mail(	'albert.shala@gmail.com',
						$_POST['email'],
						'Registration Confirmation E-Mail',
						'Your username is: ' . $username . ' Your password is:' .$password);

			$_SESSION['msg']['reg-success']='We sent you an email with your new password!';
		}
		else $err[]='This username is already taken!';
	}

	if(count($err))
	{
		$_SESSION['msg']['reg-err'] = implode('<br />',$err);
	}	
	
	header("Location: index.php");
	exit;
?>

AND THE AJAX FILE:

$(document).ready(function()
{
	$("#register_form").submit(function()
	{
		//remove all the class add the messagebox classes and start fading
		$("#msgbox2").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
		//check the username exists or not from ajax
		$.post("register.php",function(data)
        {
		  if(data=='yes') //if correct login detail
		  {
		  	$("#msgbox2").fadeTo(200,0.1,function()  //start fading the messagebox
			{ 
			  //add message and change the class of the box and start fading
			  $(this).html('Registering new users.').addClass('messageboxok').fadeTo(900,1,
              function()
			  { 
			  	 //redirect to secure page
				 document.location='register.php';
			  });
			  
			});
		  }
		  else 
		  {
		  	$("#msgbox2").fadeTo(200,0.1,function() //start fading the messagebox
			{ 
			  //add message and change the class of the box and start fading
			  $(this).html('Unable to Register, please try again.').addClass('messageboxerror').fadeTo(900,1);
			});		
          }
				
        });
 		return false; //not to post the  form physically
	});
	//now call the ajax also focus move from 
	$("#email").blur(function()
	{
		$("#register_form").trigger('submit');
	});
});

FORM:


			<form action="" method="post" id="register_form">
					<h1>Not a member yet? Sign Up!</h1>		
                    <div class="top"><span id="msgbox2" style="display:none"></span></div>

                    <?php
						
						if($_SESSION['msg']['reg-err'])
						{
							echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>';
							unset($_SESSION['msg']['reg-err']);
						}
						
						if($_SESSION['msg']['reg-success'])
						{
							echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>';
							unset($_SESSION['msg']['reg-success']);
						}
					?>
                    		
					<label class="grey" for="fname">First Name:</label>
					<input class="field" type="text" name="fname" id="fname" value="" size="23" />
					
					<label class="grey" for="lname">Last Name:</label>
					<input class="field" type="text" name="lname" id="lname" value="" size="23" />
					
					<label class="grey" for="username">Username:</label>
					<input class="field" type="text" name="username" id="username" value="" size="23" />
					
					<label class="grey" for="pass">Password:</label>
					<input class="field" type="password" name="password" id="password" value="" size="23" />
					
					<label class="grey" for="email">Email:</label>
					<input class="field" type="text" name="email" id="email" size="23" />
					
					<label>A password will be e-mailed to you.</label>
					<input type="submit" name="submit" value="Register" class="bt_register" />
					
					
				</form>

Why don’t it work, the Ajax script was meant for a login script, but I’m trying to change it so it works for my registration script, but haven’t had any luck been fussing over for a few hours and thought i’d get a second opinion on sitepoint forums.

Mm. Does the login form use Ajax too?
I’m not good at PHP,
but In my opinion, you haven’t send a callback argument in your php code,
so, i think your post function’s callback function has no argument .
$.post(“register.php”,function(data) {
alert(data); // i think it always is null.
});
try to echo some thing in you php code.
if login pass and echo “yes” else echo “no” and debug it .

Yes that’s where I think the problem is too, just can’t get my head around it, I know it’s a simple javascript variable that’s missing in order to pass the values from the script onto ajax and be processed.

Does anybody know how i modify the ajax file I posted above to accept the values I’m passing from my form and are then processed via my php file which inserts the data into my db?

Mmm…
i thought you had solve it by yourself yesterday .
your ajax code didn’t send any parameters of the form’s data to your php file(register.php).
i think you should read the jQuery API . Download one if you don’t have it.

two ways
1.using jQuery().serialize();
Serializes a set of input elements into a string of data. This will serialize all given elements.


$.get("register.php",$("#register_form").serialize() , function(data) {});
  1. code it by yourself

$.post("register.php", {
     fname: $("#fname").val(),
     lname: $("#lname").val(),
     .... // something else
}, function(data){});

I’ve actually tried doing this, but can’t see to figure out why it just doesn’t submit my values to the database?

Here’s the js code:

$(document).ready(function(){
	$("form#submit").submit(function() {
	// we want to store the values from the form input box, then send via ajax below
	var fname = $('#fname').attr('value');
	var lname = $('#lname').attr('value');
        var user = $('#user').attr('value');
        var pass = $('#pass').attr('value'); 
		
		$.ajax({
			type: "POST",
			url: "register.php",
			data: "fname="+ fname + "&lname=" + lname + "user="+ user + "pass="+ pass,
			success: function(){
				$('form#submit').hide();
				$('form#submit :input').val("submit");
				$('div.success').fadeIn();
			}
		});
	return false;
	});
});
&lt;/script&gt;

I notice that some of the keys in the data aren’t separated by ampersands. Could that be related?

Thanks pmw57, that helped! Now it’s also where the problem remains… everything works now, except for the fact that when all form values are entered, only first name and last name appear, for the other fields, it’s taking the value of lname field and inserting that instead, is there something else that needs to be used instead of an ampersand so that all values from all fields are processed and inserted into the db?

What is the full string value that is being assigned to data? That’s the first place to look.

An ampersand is mandetory to separate multiple fields.

For example: “fname=paul&lname=wilkins&user=pmw57&pass=p@$$w0rd”

this is the end result as it appears in my databaseL

First Name: b Last Name:b Last Name:b Last Name:b Last Name: 2010-11-21 04:56:03

and this is my updated data field:

data: "fname="+ fname +"& lname="+ lname + "& usr="+ usr + "& pass="+ pass + "& email="+ email

The first field is ok, as you can see First Name: b appears where it’s supposed to (I entered the field names into my form and submitted that just to show which fields were working and which not), so basically the second field which is lname is ok as well which was entered as Last Name: b, however the other three fields to follow copy the value of my second field (Last Name: b), strangely enough the last field which is a datetime field in mysql, appears fine (it’s entered as a NOW() within PHP).

How do I fix those three fields?

You could make a start by removing the spaces around those ampersands.

You could alert the data value, so that you can see directly what is being placed in there?

Ok i’ve removed the spaces, still the same and alerting the data values, how do you do that?

You can do it by placing the string values inside of an alert command.

Instead of
data: “this” + “that”

you can do
data: alert(“this” + “that”)

which will allow you to see what was being assigned to data

There are fancier ways that involve setting breakpoints in web debuggers, or my using programs like Charles to sniff the data packets, but just a simple alert will help to get you started on figuring out what information is going where.

Thanks, I tried that and it’s giving me the values I expect so fname=first name (what i typed into my form field) and &lname=last name, &usr=username, $pass=password, however email comes up as $email=undefined?

So what’s next, i can see everything except for my email value which isn’t working, but the fact is that the values are still not being displayed/entered properly into my db.

Now you look at your php code for where $_POST[‘usr’] and $_POST[‘pass’] are being handled.

this is my php code to handle the form:

$link = mysql_connect($db_host,$db_user,$db_pass) or die(‘Unable to establish a DB connection’);

mysql_select_db($db_database,$link);
                    							
$namez = mysqli_real_escape_string($link, $_POST['fname']);
$lastnamez = mysqli_real_escape_string($link, $_POST['lname']);

$sql = 'INSERT INTO table_name SET
					fname = "'.$_POST['fname'].'",
					lname = "'.$_POST['lname'].'",
					usr = "'.$_POST['lname'].'",
					pass = "'.$_POST['lname'].'",
					email = "'.$_POST['lname'].'",
					dt = NOW()';

mysql_query($sql) or die("Query failed: " . mysql_error());

Everything looks ok by me.

Take a closer look at the parts of that code which handle usr/pass/email

I see a lot of ‘lname’ strings there.