Jump to content

Problem with registration form written in PHP and AJAX


Smashden

Recommended Posts

Hello, I have registration form wirtten in PHP and AJAX + MySQL. In parts written in JavaScript I totally do not understand(I taken this  from other website which I found in http://sourceforge.net/), but I do know that when I click Submit, it's nothing happens. Can someone help me with this?

 

register.php

<?php 
/*
    Copyright (C) 2007 - 2008  Nicaw

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
include ("include.inc.php");

$account = new Account();
if ($account->load($_SESSION['account'])){
	header('location: account.php');
	die();
}else{
$ptitle="Registration - $cfg[server_name]";
include ("header.inc.php");
?>
<div id="content">
<div class="top_page">Registration</div>
<div class="mid_page">
	<table>
		<tr>
			<td width="40%" style="vertical-align: top">
				<label for="email"><b>Email address:</b></label>
			</td>
			<td width="60%"><input id="email" type="text" /> <span id="email_state"></span>
				<div><?php
				if ($cfg['Email_Validate']) {
					echo 'This server requires email validation. A letter with your password will be sent to the address provided above.';
				} else {
					echo 'Please enter a valid email address if we need to contact you.';
				}
				?></div>
			</td>
		</tr>
		<tr>
			<td width="40%" style="vertical-align: top"><label for="accname"><b>Desired Account Name:</b></label></td>
				<td width="60%"><input id="accname" type="text" /> <span id="accname_state"></span>
				<div>Account name consists of letters a-z, numbers 0-9, underscores _ and is at least 6 characters long.</div>
			</td>
		</tr>
		<?php
		if (!$cfg['Email_Validate']) {?>
		<tr>
			<td style="vertical-align: top"><label for="password"><b>Choose a password:</b></label></td>
			<td>
				<input id="password" type="password" /> <span id="password_state"></span>
				<div>Password consists of letters a-z, numbers 0-9, symbols(~!@#%&;,:\^$.|?*+()) and is at least 6 characters long.	</div>
			</td>
		</tr>
		<tr>
			<td style="vertical-align: top"><label for="confirm"><b>Re-enter password:</b></label></td>
			<td><input id="confirm" type="password" /> <span id="confirm_state"></span><br/><br/></td>
		</tr>
		<?php } ?>
		<tr>
			<td style="vertical-align: top"><label for="rlname"><b>*Your name:</b></label></td>
			<td><input id="rlname" type="text" /><br/><br/></td>
		</tr>
		<tr>
			<td style="vertical-align: top"><label for="location"><b>*Your location:</b></label></td>
			<td><input id="location" type="text" /><br/>* Optional fields<br/><br/></td>
		</tr>
		<?php
		if($cfg['use_captcha']) {
			echo '<tr><td style="vertical-align: top"><b>Verification:</b></td><td><div class="g-recaptcha" data-sitekey="my site key"></div>'.
			'</td></tr>';
		}
		?>
		<tr>
			<td colspan="2">
				<div style="overflow-y: scroll; height: 200px;"><?php echo htmlspecialchars(@file_get_contents('documents/server_rules.txt'));?></div>
				<input id="rules_check" type="checkbox" onclick="onRulesCheck(this)"/> <label for="rules_check"><b>I agree with server rules</b></label> 
				<button id="submit_button" disabled="disabled" onclick="onSubmit()">Submit</button>
				<span id="submit_load" style="color: red; font-weight: bold; text-decoration: blink;"></span>
				<div id="submit_errors" style="color: red; font-weight: bold;"></div>
				<div id="submit_success" style="color: green; font-weight: bold;"></div>
			</td>
		</tr>
	</table>

	
	<script type="text/javascript">
	//<![CDATA[
	function onRulesCheck(node) {
		if (node.checked) {
			node.disabled = true;
			$('#submit_button').prop( "disabled", false);
		}
	}

	function onSubmit() {
		var params = new Array();
		params['email'] = $('email').value;
		params['accname'] = $('accname').value;

		params['rlname'] = $('rlname').value;
		params['location'] = $('location').value;
		params['captcha'] = $('captcha').value;
		params['submit'] = 'yes';
		<?php if (!$cfg['Email_Validate']) {?>
		params['password'] = $('password').value;
		params['confirm'] = $('confirm').value;
		<?php } else { ?>
		$('submit_load').innerHTML = 'Please wait...';
		<?php } ?>
		$('submit_button').disabled = true;
		new Ajax.Request('modules/account_create.php', {
			method: 'post',
			parameters: params,
			onSuccess: function(transport) {
				var param = transport.request.options.parameters;
				var XML = parseXML(transport.responseText);
				var errors = XML.getElementsByTagName('error');
				var success = XML.getElementsByTagName('success');
				$('submit_errors').innerHTML = '';
				$('submit_success').innerHTML = '';
				$('submit_load').innerHTML = '';
				
				for (var i = 0; i < errors.length; i++) {
					$('submit_errors').innerHTML += errors[i].attributes.getNamedItem('id').value + ': ' + errors[i].childNodes[0].nodeValue + '<br/>';
				}
				if (success.length > 0) {
					$('submit_success').innerHTML = success[0].childNodes[0].nodeValue;
				} else {
					$('submit_button').disabled = false;
				}
				$('captcha_img').src = 'doimg.php?' + Date.parse(new Date().toString());

			},
			onFailure: function() {alert('AJAX failed.')}
		});
	}

	function updateState(id, XML) {
			if($(id).value == '') {
				$(id+'_state').innerHTML = '';
				return;
			}
			var errors = XML.getElementsByTagName('error');
			for (var i = 0; i < errors.length; i++) {
				if (errors[i].attributes.getNamedItem('id').value == id) {
					$(id+'_state').innerHTML = '<img src="resource/cross.png" alt="X" title="'+errors[i].childNodes[0].nodeValue+'"/>';
					return;
				}
			}
			$(id+'_state').innerHTML = '<img src="resource/tick.png" alt="V" />';
		}

	var observerCallback = function(el, value) {
		var params = new Array();
		params['el_id'] = el.id;
		params['email'] = $('email').value;
		params['accname'] = $('accname').value;
	<?php if (!$cfg['Email_Validate']) {?>
		params['password'] = $('password').value;
		params['confirm'] = $('confirm').value;
	<?php } ?>
		new Ajax.Request('modules/account_create.php', {
				method: 'post',
				parameters: params,
				onSuccess: function(transport) {
					var param = transport.request.options.parameters;
					var XML = parseXML(transport.responseText);
					if (param.el_id == 'accname') {
						updateState('accname', XML);
						updateState('password', XML);
					} else if (param.el_id == 'password') {
						updateState('password', XML);
						updateState('confirm', XML);
					} else {
						updateState(param.el_id, XML);
					}
				},
				onFailure: function() {alert('AJAX failed.')}
		});
	}

	new Form.Element.Observer('email', 2, observerCallback);
	new Form.Element.Observer('accname', 2, observerCallback);
	<?php if (!$cfg['Email_Validate']) {?>
	new Form.Element.Observer('password', 2, observerCallback);
	new Form.Element.Observer('confirm', 2, observerCallback);
	<?php } ?>
	//]]>
	</script>	
</div>
<div class="bot_page"></div>
</div>
<?php 
}
include ("footer.inc.php");
?>

and this is account_create.php which is include in AJAX

<?php
/*
    Copyright (C) 2007 - 2008  Nicaw
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
include ("../include.inc.php");
 
$errors = array();
$account = new Account();

if ($cfg['use_captcha'] && isset($_POST['submit'])) {
    // To do
}

//email formating rules
if (empty($_POST['email'])) {
    $errors['email'] = 'empty email address';
}elseif (!preg_match('/^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$/i',$_POST['email'])) {
    $errors['email'] = 'not a valid email address';
}else {
    $email = $_POST['email'];
}

//account name formating rules
if (empty($_POST['accname'])) {
    $errors['accname'] = 'empty account name';
}elseif (!preg_match('/^[A-Z0-9_]{6,30}$/i',$_POST['accname'])) {
    $errors['accname'] = 'not a valid account name';
}else {
//check for existing name
    if($account->existsName(strtolower($_POST['accname']))) {
        $errors['accname'] = 'account name is already used';
    } else {
        $accname = strtolower($_POST['accname']);
    }
}

//password formating rules
if ($cfg['Email_Validate']) {
    $password = substr(str_shuffle(strtolower('qwertyuipasdfhjklzxcvnm12345789')), 0, ;
} else {
    if (empty($_POST['password'])) {
        $errors['password'] = 'empty password';
    }elseif (!strlen($pass) > 5 && strlen($pass) <= 50 && preg_match('/^[a-zA-Z0-9~!@#%&;,:\\\^\$\.\|\?\*\+\(\)]*$/',$_POST['password'])) {
        $errors['password'] = 'not a valid password';
    }elseif (isset($_POST['accname']) && strtolower($_POST['password']) == strtolower($_POST['accname'])) {
        $errors['password'] = 'password cannot match account name';
    }elseif (empty($_POST['confirm'])){
        $errors['confirm'] = 'empty password';
    }elseif ($_POST['password'] != $_POST['confirm']) {
        $errors['confirm'] = 'passwords do not match';
    }else {
        $password = $_POST['password'];
    }
}

$responseXML = new SimpleXMLElement('<response/>');
if (count($errors) > 0) {
    while ($error = current($errors)) {
        $err = $responseXML->addChild('error', $error);
        $err->addAttribute('id', key($errors));
        next($errors);
    }
}elseif (count($errors) == 0 && isset($_POST['submit'])) {

    //create the account
	$account->saveAccount($accname, $password, $email, substr($_POST['rlname'], 0, 50), substr($_POST['location'], 0, 50));

    if ($cfg['Email_Validate']) {
        $body = "Here is your login information for <a href=\"http://$cfg[server_url]/\">$cfg[server_name]</a><br/>
<b>Account name:</b> $accname<br/>
<b>Password:</b> $password<br/>
<br/>
Powered by <a href=\"http://nicaw.net/\">Nicaw AAC</a>";
        //send the email
        require_once("../class/class.phpmailer.php");

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->IsHTML(true);
        $mail->Host = $cfg['SMTP_Host'];
        $mail->Port = $cfg['SMTP_Port'];
        $mail->SMTPAuth = $cfg['SMTP_Auth'];
        $mail->Username = $cfg['SMTP_User'];
        $mail->Password = $cfg['SMTP_Password'];

        $mail->From = $cfg['SMTP_From'];
        $mail->AddAddress($email);

        $mail->Subject = $cfg['server_name'].' - Login Details';
        $mail->Body    = $body;

        if ($mail->Send()) {
        //create new message
            $responseXML->addChild('success', 'Your login details were emailed to '.htmlspecialchars($_POST['email']));
        }else {
            $responseXML->addChild('success', 'Contact administrator to get your password. Mailer Error: '.$mail->ErrorInfo);
        }
    }else {
    //create new message
        $responseXML->addChild('success', 'Account created!');
        $account->logAction('Created');
    }
}
echo $responseXML->asXML();
?>
Link to comment
Share on other sites

Okay. Have you verified if your onSubmit() handler is being called? You can either use a breakpoint or just put a simple alert at the very top of it to confirm.

 

If your handler is working, then the easiest way is to use the debugging tools to step through it and find where it's breaking.

 

Are you getting any JS errors? Have you looked in the network pane of the debugger to see if a new network request is being made after you click submit?

Link to comment
Share on other sites

I added below function onSubmit() { this:

alert("Test!!");

and it is showed when I click.

I look to network panel and there is: 

Uncaught ReferenceError: Ajax is not defined

 

Error in that line:

new Ajax.Request('modules/account_create.php', {

 

 

EDIT:

I add this to main file

<script language="javascript" type="text/javascript" src="prototype.js"></script>

 

and now I don't have any errors but this no working again

Edited by Smashden
Link to comment
Share on other sites

I download Firefox and install Firebug and I think there this is error:

		new Ajax.Request('modules/account_create.php', {
			method: 'post',
			parameters: params,
			onSuccess: function(transport) {
				var param = transport.request.options.parameters;
				var XML = parseXML(transport.responseText);
				var errors = XML.getElementsByTagName('error');
				var success = XML.getElementsByTagName('success');
				$('#submit_errors').innerHTML = '';
				$('#submit_success').innerHTML = '';
				$('#submit_load').innerHTML = '';
				
				for (var i = 0; i < errors.length; i++) {
					$('#submit_errors').innerHTML += errors[i].attributes.getNamedItem('id').value + ': ' + errors[i].childNodes[0].nodeValue + '<br/>';
				}
				if (success.length > 0) {
					$('#submit_success').innerHTML = success[0].childNodes[0].nodeValue;
				} else {
					$('#submit_button').prop( "disabled", false);
				}

			},
			onFailure: function() {alert('AJAX failed.')}
		}); 

In response i have:

<response><error id="email">empty email address</error><error id="accname">empty account name</error><error id="password">empty password</error></response>

Edited by Smashden
Link to comment
Share on other sites

In Chrome Developer Tools you simply have to open the Network tab and then click your button. The Network tab has to be opened before you click the button, otherwise nothing will show up. If you get a request to show up you can then click it and inspect the request body to see what kind of data was sent.

 

post-125590-0-86072300-1443707480_thumb.png
 

Edited by scootstah
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.