I'm working on a program but I'm new to js/jQuery/Ajax. I am trying to get user input from a form (html) and send it over to a php file that will insert the data into a MySQL database and then ultimately spit out the information into a div. I press submit but my user submitted data does not get inserted into the database. I initially had the submission redirect to my php file through the tag (action="post.php") which had worked in terms of inserting the data into the mysql database but had also redirected it to that post.php file upon submission.
my js file datawire.js:
$( 'button#submit').on('click', function() {
var uName = $('input#uName').val();
var uMessage = $('input#uMessage').val();
if ($.trim(uName) != '' && $.trim(uMessage) != '') {
$.post('post.php', {username: uName, message: uMessage}, function(data) {
$('div#viewer').text(data);
});
}
});
My php file post.php
<?php include("config.php");
$username = isset($_POST['username']);
$message = isset($_POST['message']);
if (($username && $message) && (empty($_POST['username'] === false) && empty($_POST['message']) === false)) {
$username = $_POST['username'];
$message = $_POST['message'];
// insert into database
$nowTime = getDateTime();
$userIp = getIp();
$sql = "INSERT INTO commentdb (id,username, message,date,ip) VALUES ('','$username','$message', '$nowTime', '$userIp') ";
$result = mysql_query($sql);
}
?>
and my HTML file:
<html>
<head>
<!-- latest jQuery direct from google -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- for getting data -->
<script src="datawire.js"></script>
<!-- for posting data -->
<script type="text/javascript">
$(document).ready(function() {
$('#viewer').load("getdata.php");
});
</script>
</head>
<body>
<div id="viewer"> </div>
<br>
<!-- User form -->
<form method='post'>
<input type="text" id="uName" name="username" placeholder="Name" value="" maxlength="15" />
<br />
<input type="text" id="uMessage" name="message" placeholder="Message" value="" maxlength="100" />
<br />
<button id="submit" type="submit">Submit!</button> <button type="reset">Clear!</button>
</form>
</body>
</html>
Try wrapping the contents of datawire.js with $(document).ready like you did in html file. This insures $ is actually defined before it's used.
Prevent your form submit with preventDefault() function
$( 'button#submit').click(function(e) {
e.preventDefault();
var uName = $('input#uName').val();
var uMessage = $('input#uMessage').val();
if ($.trim(uName) != '' && $.trim(uMessage) != '') {
$.post('post.php', {username: uName, message: uMessage}, function(data) {
$('div#viewer').text(data);
});
}
});
Return the text message from the server like this
<?php include("config.php");
$username = isset($_POST['username']);
$message = isset($_POST['message']);
if (($username && $message) && (empty($_POST['username'] === false) && empty($_POST['message']) === false)) {
$username = $_POST['username'];
$message = $_POST['message'];
// insert into database
$nowTime = getDateTime();
$userIp = getIp();
$sql = "INSERT INTO commentdb (id,username, message,date,ip) VALUES ('','$username','$message', '$nowTime', '$userIp') ";
$result = mysql_query($sql);
if($result)
{
echo " Data Inserted Successfully";
}else{
echo " Data insert failed - ".mysql_error();
}
}else{
echo " Required fields are missing";
}
?>
Related
I have never worked with $_COOKIES, and now I've been given the task to make it work.
I have been following a couple of tutorials online.
Found here: http://www.phpnerds.com/article/using-cookies-in-php/2
And then here:https://www.youtube.com/watch?v=Dsem42810H4
Neither of which worked for me.
Here is how my code ended up. I shortened it as much as I could.
Starting with the index.php page, which contains the initial login form:
<form role="form" action="index.php" method="post" id="loginForm" name="loginForm">
<input type="text" class="form-control" id="username" name="username"
value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" />
<input type="password" class="form-control" id="password" name="password"
value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>"/>
<button type="button" id="loginSubmit" name="loginSubmit" class="btn btn-primary btn-block btn-flat">Sign In</button>
<input type="checkbox" id="rememberme"
<?php if(isset($_COOKIE['username'])){echo "checked='checked'";} ?> value="1" />
</form>
Here is the JavaScript used to send the form values:
$('#loginSubmit').on('click', function()
{
var username = $('#username').val();
var password = $('#password').val();
var rememberme = $('#rememberme').val();
// skipping the form validation
$.post('api/checkLogin.php', {username: username, password: password, rememberme:rememberme}, function(data)
{
// the data returned from the processing script
// determines which page the user is sent to
if(data == '0')
{
console.log('Username/Password does not match any records.');
}
if(data == 'reg-user")
{
window.location.href = "Home.php";
}
else
{
window.location.href = "adminHome.php";
}
});
});
Here is the processing script, called checkLogin.php. This is where I attempt to set the $_COOKIE:
<?php
include ("../include/sessions.php");
if(isset($_POST['username']) && isset($_POST['password']))
{
$username = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($dbc, trim($_POST['password'])));
$rememberme = $_POST['rememberme'];
$select = "SELECT username, fullname, password FROM users WHERE username = '".$username."'";
$query = mysqli_query($dbc, $select);
$row = mysqli_fetch_array($query);
$dbusername = htmlentities(stripslashes($row['username']));
$dbfullname = htmlentities(stripslashes($row['fullname']));
$dbpassword = htmlentities(stripslashes($row['password']));
if(password_verify($password, $dbpassword))
{
// setting sessions here
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $dbfullname;
// here is where I attempt to set the $_COOKIE
if(isset($remember))
{
setcookie('username', $_POST['username'], time()+60*60*24*365);
setcookie('password', $_POST['password'], time()+60*60*24*365);
}
else
{
setcookie('username', $_POST['username'], false);
setcookie('password', $_POST['password'], false);
}
echo $username; // this gets sent back to the JavaScript
mysqli_free_result($query);
}
else
{
// username/password does not match any records
$out = 0;
echo $out;
}
}
?>
So now that I have attempted to set the $_COOKIE, I can try to print it to the home page, like so:
<?php echo 'cookie ' . $_COOKIE["username"]; ?>
To which does not work, because all I see is the word 'cookie'.
Besides that, when I log out, I am hoping to see the login form already filled out, which is the overall task I have been trying to complete, but have been unsuccessful at doing so.
What I am trying to achieve is have the form appear if there was nothing submitted. So I add the form html to a variable and then echo the variable inside the html.
However ever since I implemented AJAX, inside the #results div. It also exports the jquery.js and my ajax script.
If I remove the PHP else code that displays the form, I won't see the form at all.
So how would someone make sure the js scripts aren't being inserted where they shouldn't be?
PHP:
if( isset($_POST["u_name"]) && isset($_POST["u_lastname"]) && isset($_POST["u_email"]) ){
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO testTable (Name, Lastname, Email)
VALUES ('".$_POST["u_name"]."','".$_POST["u_lastname"]."','".$_POST["u_email"]."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."";
}
$conn->close();
}else {
$final_content = '<form action="script.php" method="post" id="user_form">
<input type="text" name="u_name" placeholder="Name" id="user_name"> <br>
<input type="text" name="u_lastname" placeholder="Lastname" id="user_lastname"> <br>
<input type="email" name="u_email" placeholder="Email" id="user_email"> <br>
<input type="submit" value="Submit" name="submit">
</form>';
}
?>
HTML
<html>
<head>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
//Set form variable
var form = $("#user_form");
form.submit(function(event){
//Set data variables
var user_name = $("#user_name").val();
var user_lastname = $("#user_lastname").val();
var user_email = $("#user_email").val();
//Check if values are set
if( ($.trim(user_name) != "") && ($.trim(user_lastname) != "") && ($.trim(user_email) != "") ){
$.post("script.php", {u_name: user_name, u_lastname: user_lastname, u_email: user_email}, function(data){
$("#results").html(data);
});
}
event.preventDefault();
});
});
</script>
</head>
<body>
<?php echo $final_content ?>
<div id="results"></div>
</body>
</html>
Add an exit(); right after $conn->close();, just above the else.
This will make sure that once you have output the results, you do not continue with the rest of the code (not included in your question) where you output the full HTML page with script tags and <div id="results"> ...etc.
Apparently that display code is not all inside the else block, but also further down, after the else block.
Okay so i made a login button and this is the function code, But it keeps showing the error " Login unsuccessful, Please try again... "
Thank you in advance...
I didn't really get what you were asking for so i put almost all the code in cause i am trying and trying and can't figure it out...
<?php
include_once ("php_includesss121/check_login_statusopop.php");
// If user is already logged in, header that user away
if ($user_ok == true)
{
header("location: user.php?u=" . $_SESSION["username"]);
exit();
}
?><?php
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if (isset($_POST["e"]))
{
// CONNECT TO THE DATABASE
include_once ("php_includesss121/db_conxx12.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES AND SANITIZE
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = md5($_POST['p']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// FORM DATA ERROR HANDLING
if ($e == "" || $p == "")
{
echo "login_failed";
exit();
}
else
{
// END FORM DATA ERROR HANDLING
$sql = "SELECT id, username, password FROM users WHERE email='$e' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_id = $row[0];
$db_username = $row[1];
$db_pass_str = $row[2];
if ($p != $db_pass_str)
{
echo "login_failed";
exit();
}
else
{
// CREATE THEIR SESSIONS AND COOKIES
$_SESSION['userid'] = $db_id;
$_SESSION['username'] = $db_username;
$_SESSION['password'] = $db_pass_str;
setcookie("id", $db_id, strtotime('+30 days') , "/", "", "", TRUE);
setcookie("user", $db_username, strtotime('+30 days') , "/", "", "", TRUE);
setcookie("pass", $db_pass_str, strtotime('+30 days') , "/", "", "", TRUE);
// UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS
$sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo $db_username;
exit();
}
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Log In</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="style/style.css">
<script src="js/mainopop.js"></script>
<script src="js/ajaxopop.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function login(){
var e = _("email").value;
var p = _("password").value;
if(e == "" || p == ""){
_("status").innerHTML = "Fill out all of the form data";
} else {
_("loginbtn").style.display = "none";
_("status").innerHTML = 'Please wait...';
var ajax = ajaxObj("POST", "login.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "login_failed"){
_("status").innerHTML = "Login unsuccessful, Please try again...";
_("loginbtn").style.display = "block";
} else {
window.location = "user.php?u="+ajax.responseText;
}
}
}
ajax.send("e="+e+"&p="+p);
}
}
</script>
</head>
<body>
<?php
include_once ("template_pageTopLoginPageopop.php"); ?>
<div id="pageMiddle">
<h2>Welcome ...</h2>
<h3>Log In Here</h3>
<!-- LOGIN FORM -->
<form id="loginform" onsubmit="return false;">
<div>Email Address:</div>
<input type="text" id="email" onfocus="emptyElement('status')" maxlength="300">
<div>Password:</div>
<input type="password" id="password" onfocus="emptyElement('status')" maxlength="100">
<br />
<br />
<button id="loginbtn" onclick="login()">Log In</button>
<p id="status"></p>
Forgot Your Password?
</form>
<!-- LOGIN FORM -->
</div>
<?php
include_once ("template_pageBottomopop.php");
?>
</body>
</html>
And Javascript file ajaxopop.js:
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x) {
if (x.readyState == 4 && x.status == 200) {
return true;
}
}
Please note that password in DB Table should be md5
encrypted as in PHP, you are encrypting it to match further. If not, just remove md5 encryption from PHP Code.
I am trying to learn from an example from online,for a login form with php and jquery and i am using the exactly the same example, but for some reason the AJAX isnt getting anything back but redirecting my to another php.
Here is a link of what i had been trying and the problem.
http://rentaid.info/Bootstraptest/testlogin.html
It supposed to get the result and display it back on the same page, but it is redirecting me to another blank php with the result on it.
Thanks for your time, i provided all the codes that i have, i hope the question isnt too stupid.
HTML code:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form id= "loginform" class="form-horizontal" action='http://rentaid.info/Bootstraptest/agentlogin.php' method='POST'>
<p id="result"></p>
<!-- Sign In Form -->
<input required="" id="userid" name="username" type="text" class="form-control" placeholder="Registered Email" class="input-medium" required="">
<input required="" id="passwordinput" name="password" class="form-control" type="password" placeholder="Password" class="input-medium">
<!-- Button -->
<button id="signinbutton" name="signin" class="btn btn-success" style="width:100px;">Sign In</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javasript" src="http://rentaid.info/Bootstraptest/test.js"></script>
</body>
</html>
Javascript
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
$("#loginform").submit(function() {
return false;
});
}
});
php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
ob_start();
session_start();
include 'connect.php';
//get form data
$username = addslashes(strip_tags($_POST['username']));
$password = addslashes(strip_tags($_POST['password']));
$password1 = mysqli_real_escape_string($con, $password);
$username = mysqli_real_escape_string($con, $username);
if (!$username || !$password) {
$no = "Please enter name and password";
echo ($no);
} else {
//log in
$login = mysqli_query($con, "SELECT * FROM Agent WHERE username='$username'")or die(mysqli_error());
if (mysqli_num_rows($login) == 0)
echo "No such user";
else {
while ($login_row = mysqli_fetch_assoc($login)) {
//get database password
$password_db = $login_row['password'];
//encrypt form password
$password1 = md5($password1);
//check password
if ($password1 != $password_db)
echo "Incorrect Password";
else {
//assign session
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
}
}
}
}
?>
Edit
$("button#signinbutton").click(function(){
if($("#username").val() ==""||$("#password").val()=="")
$("p#result).html("Please enter both userna");
else
$.post ($("#loginform").attr("action"),
$("#loginform:input").serializeArray(),
function(data) {
$("p#result).html(data); });
});
$("#loginform").submit(function(){
return false;
});
First of all, Remove :-
header("Location: http://rentaid.info/Bootstraptest/aboutus.html");
and if you want to display the data, echo username and password.
$_SESSION['username'] = $username;
$_SESSION['password'] = $password1;
echo $username."<br>".;
echo $password1;
The reason you are being redirected is that you are also calling $.submit. The classic form submit will redirect you to a new page, which is exactly what you don't want when you're using AJAX. If you remove this call:
$("#loginform").submit(function() {
return false;
});
you probably should have working solution. If not, let me know :)
Modify your javascript section so that
$("button#signinbutton").click(function() {
if ($("#username").val() == "" || $("#password").val() == "") {
$("p#result).html("Please enter both userna");
} else {
$.post($("#loginform").attr("action"), $("#loginform:input").serializeArray(), function(data) {
$("p#result").html(data);
});
}
});
$("#loginform").submit(function() {
return false;
});
is outside the function call.
So I have a problem with my registration and login php code. I have put them together in one php file called index.php and the registration works fine but when i try to login it clashes with the registration statements.
<?php
include_once("php_includes/check_login_status.php");
// If user is already logged in, header that weenis away
if($user_ok == true){
header("location: user.php?u=".$_SESSION["username"]);
exit();
}
?>
<!-- .registerphp -->
<?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("php_includes/db_conx.php");
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?>
<?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
include_once ("php_includes/blowfish.php");
$cryptpass = crypt($p);
$p_hash = cryptPass($cryptpass)."$cryptpass".cryptPass($cryptpass);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (username, email, password, gender, country, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p_hash','$g','$c','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "auto_responder#pfolio.bugs3.com";
$subject = 'PFolio Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>PFolio Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;"><img src="http://www.pfolio.bugs3.com/images/smalllogo.png" width="215" height="50" alt="PFolio" style="border:none; float:left;">PFolio Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* Username: <b>'.$u.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
<!-- .registerphp -->
<!-- .loginphp -->
<?php
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("php_includes/db_conx.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES AND SANITIZE
$u = mysqli_real_escape_string($db_conx, $_POST['u']);
$p = crypt($_POST['p']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// FORM DATA ERROR HANDLING
if($u == "" || $p == ""){
echo "login_failed";
exit();
} else {
// END FORM DATA ERROR HANDLING
$sql = "SELECT id, username, password FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_id = $row[0];
$db_username = $row[1];
$db_pass_str = $row[2];
if($p != $db_pass_str){
echo "login_failed";
exit();
} else {
// CREATE THEIR SESSIONS AND COOKIES
$_SESSION['userid'] = $db_id;
$_SESSION['username'] = $db_username;
$_SESSION['password'] = $db_pass_str;
setcookie("id", $db_id, strtotime( '+30 days' ), "/", "", "", TRUE);
setcookie("user", $db_username, strtotime( '+30 days' ), "/", "", "", TRUE);
setcookie("pass", $db_pass_str, strtotime( '+30 days' ), "/", "", "", TRUE);
// UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS
$sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo $db_username;
exit();
}
}
exit();
}
?>
<!-- .loginphp -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<!--[if lt IE 9]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<title>P'Folio</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="css/loginstyle.css" rel="stylesheet" type="text/css">
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<!-- .registerjs -->
<script>
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "index.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "index.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g);
}
}
</script>
<!-- .registerjs -->
<!-- .loginjs -->
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function login(){
var u = _("user_name").value;
var p = _("pass_word").value;
if(u == "" || p == ""){
_("sta_tus").innerHTML = "Fill out all of the form data";
} else {
_("loginbtn").style.display = "none";
_("sta_tus").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "index.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "login_failed"){
_("sta_tus").innerHTML = "Login unsuccessful, please try again.";
_("loginbtn").style.display = "block";
} else {
window.location = "user.php?u="+ajax.responseText;
}
}
}
ajax.send("u="+u+"&p="+p);
}
}
</script>
<!-- .loginjs -->
</head>
<body>
<!-- .wrapper -->
<div class="wrapper">
<!-- .header-->
<header class="header"> <img src="images/logo.png" alt="logo" title="P'Folio"> </header>
<!-- .header-->
<!-- .login -->
<div class="login">
<form id="loginform" onsubmit="return false;">
<div><img class="h1" src="images/lh.png" alt="login%20here"/></div>
<div><img class="p1" src="images/wb.png" alt="welcome%20back"/></div>
<input type="text" id="user_name" onfocus="emptyElement('status')" maxlength="16" class="loginboxes" placeholder="Username">
<input type="password" id="pass_word" onfocus="emptyElement('status')" maxlength="100" class="loginboxes" placeholder="Password">
<br />
<button id="loginbtn" onclick="login()">Log In</button>
<p id="sta_tus"></p>
Forgot Your Password?
</form>
</div>
<!-- .login -->
<!-- .main -->
<main class="content">
<p>Are you a musician, a model, actor or actress or anyone with a talent then sign up for P'Folio.
Here on P'Folio we look to give you space to upload a portfolio for you to be noticed. </p>
</main>
<!-- .main -->
<!-- .signup -->
<div class="signup">
<form name="signupform" id="signupform" onsubmit="return false;">
<div><img class="h1" src="images/caa.png" alt="create%20account"/></div>
<div><img class="p1" src="images/ntm.png" alt="new%20to%20P'Folio"/></div>
<span id="unamestatus"></span>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16" placeholder="Username" class="registerboxes">
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88" placeholder="Email" class="registerboxes">
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="100" placeholder="Password" class="registerboxes">
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="100" placeholder="Confirm Password" class="registerboxes">
<select id="gender" onfocus="emptyElement('status')" class="registerboxes">
<option value="0" selected="selected">Choose...</option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<select id="country" onfocus="emptyElement('status')" class="registerboxes">
<?php include_once("template_country_list.php"); ?>
</select>
<div class="conditions">By clicking Sign Up,
you agree to our Terms and that
you have read our Privacy Policy ,
including our Cookie Use .</div>
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
</div>
<!-- .signup -->
<!-- .footer -->
<footer class="footer">
<div id="legal"><a class="legal" href="JavaScript:newPopup('Login/Legal/Terms.php');">Terms</a> | <a class="legal" href="JavaScript:newPopup('Login/Legal/Privacy.php');">Privacy</a></div>
<div id="font"><a class="font">P'folio © 2014</a></div>
</footer>
<!-- .footer -->
</div>
<!-- .wrapper -->
</body>
</html>
Why is my Registration and Login code not working?
For registration and also login don't use AJAX. It is better. You may use classic JavaScript for pre-checking of correct setting of username and password, but don't use AJAX for own login and registration process.
Also it is good to split both processes into different places. I have not ever seen any web where login and registration would be done from the same place - and via AJAX.
For username checking you may use order
preg_match('/^[^0-9][a-z0-9]{3,16}/i', $_POST['username']);
that checks if username does not start with number and is long at least 3 signs and not longer than 16 signs. Also it allows small letters and numbers.