Form is not posting / running the script - javascript

I am using a register script but by some reason this script is not working.
First of all here is my <html> form:
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<legend>Member Registration</legend>
<p><label>Username:</label><input name="username" type="text" maxlength="20" <?php if(isset($error)) {echo "value='$username'";} ?> /></p>
<p><label>Password:</label><input name="password" type="password" maxlength="20" /></p>
<p><label>Confirm Password:</label><input name="password2" type="password" maxlength="20" /></p>
<p><label>Email:</label><input name="email" type="text" maxlength="255" <?php if(isset($error)) {echo "value='$email'";} ?> /></p>
<p><input type="submit" name="submit" value="Register"></p>
</form>
After clicking on the submit button the script needs to get posted. Before adding the values to the database the php script should do a check:
if (strlen($username) < 3){
$error[] = 'User name must be between 3 and 20 characters.';
}
When I enter just 1 character also this is not checked. When I click on the submit button the script returns into its first state.
Why is this happening? I have set the reporting of errors on, but also when I do that I dont get any error message.
How can I fix this problem?
Here is my full PHP code:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'db';
$conn = mysqli_connect ($dbhost, $dbuser, $dbpass);
$conn = mysqli_select_db ($conn, $dbname);
if(!$conn){
die( "Sorry! There seems to be a problem connecting to our database. Please give us a few minutes to remedy the problem. Thank you.");
}
function errors($error){
if (!empty($error))
{
$i = 0;
while ($i < count ($error)){
echo '<span class="warning">'.$error[$i].'</span>';
$i ++;
}
}
if (isset($_POST['submit'])){
$username = trim($_POST['username']);
if (strlen($username) < 3){
$error[] = 'User name must be between 3 and 20 charactors.';
}
if(!get_magic_quotes_gpc()){
$POST[] = addslashes($_POST['username']);
}
$usercheck = $_POST['username'];
$check = mysqli_query($conn, "SELECT username FROM users WHERE username ='".$usercheck."'")or die(mysqli_error());
$check2 = mysqli_num_rows($check);
if ($check2 != 0) {
$error[] = 'Sorry, the username <b>'.$_POST['username'].'</b> is already in use.';
}
$password = trim($_POST['password']);
if (strlen($password) < 5) {
$error[] = 'password Must be between 5 and 20 characters.';
}
if ($_POST['password'] != $_POST['password2']) {
$error[] = 'Your passwords did not match.';
}
if (!get_magic_quotes_gpc()) {
$_POST[] = addslashes($_POST['email']);
}
$emailcheck = $_POST['email'];
$hash = md5( rand(0,1000) );
$emailcheck1 = mysqli_query($conn, "SELECT email FROM members WHERE email = '".$emailcheck."'")or die(mysqli_error());
$emailcheck2 = mysqli_num_rows($emailcheck1);
if ($emailcheck2 != 0) {
$error[] = 'Sorry, the email address <b>'.$_POST['email'].'</b> is already in use, Please choose another email address.';
}
if (!$error ) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(!get_magic_quotes_gpc())
{
$username = addslashes($username);
$password = addslashes($password);
$email = addslashes($email);
}
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
$email = mysqli_real_escape_string($email);
$username = strip_tags($username);
$password = strip_tags($password);
$email = strip_tags($email);
$username = ucwords(strtolower($username));
$email = strtolower($email);
$insert1 = "INSERT INTO members (username, password, email) VALUES ('$username', md5('$password'), '$email')";
$result1 = mysqli_query($insert1) or die('Error : ' . mysqli_error());
}
}
}
?>

Related

Login redirect using jquery

i'll be glad if anyone can help out am working on a login system using jquery but i encounter a problem
what i want to achieve is user filling out their details on the login page and i'll process it using jQuery at the back end without reloading the page, i have achive that but the problem now is when the details they provide and the details in the database is correct i want to redirect them to another page
here is my login form
<form class="form-login" id="loginmyForm" method="post">
<input class="input input_auth" type="text" name="loginemail" id="loginemail" placeholder="E-mail" required />
<span id="loginError_username" class="error error-opacit"></span>
<input class="input input_auth" type="password" name="loginpassword" id="loginpassword" placeholder="Password" required />
<span id="loginError_password" class="error error-opacit"></span>
<input type="hidden" name="source" value="login" id="source">
<button class="btn pulse input_auth" type="button" id="submitFormData" onclick="loginSubmitFormData();" value="Submit">Login</button>
<div class="forgot-password">
<a id="forgotPass" href="#" class="link-btn open-modal" data-openModal="modal-recovery">Forgot your password?</a>
</div>
Here is jquery code
<script type="text/javascript">
function loginSubmitFormData() {
var loginemail = $("#loginemail").val();
var loginpassword = $("#loginpassword").val();
var source = $("#source").val();
$.post("authlogin.php", { loginemail: loginemail, loginpassword: loginpassword },
function(data) {
$('#loginresults').html(data);
$('#loginmyForm')[0].reset();
});
}
</script>
And here is the login authentication authlogin.php
<?php
session_start();
include 'config/info.php';
// get the details from form
$email=$_POST['loginemail'];
$password = stripslashes($_REQUEST['loginpassword']);
$password = mysqli_real_escape_string($conn,$password);
$sql="SELECT * FROM user_info WHERE email='".$email."'";
$result = mysqli_query($conn,$sql);
$Countrow = mysqli_num_rows($result);
if ($Countrow == 1) {
$fetchrow = mysqli_fetch_assoc($result);
$loginpassword = $fetchrow['password'];
// Verify the password here
if (password_verify($password, $loginpassword)) {
$_SESSION['email'] = $email;
//setcookie('username', $adminID, time() + (86400 * 30), "/");
$date = date('Y-m-d H:i:s');
$ActivityStmt = "INSERT INTO login_activity (`email`, `last_login`, `browser`, `os`, `ip_address`) VALUES('".$email."', '".$date."', '".$gen_userBrowser."', '".$gen_userOS."', '".$gen_userIP."')";
$ActivityResult = mysqli_query($conn, $ActivityStmt);
echo 'Login Successfully! Click to proceed';
exit();
}
else{
echo 'Incorrect Password';
exit();
}
}
else{
echo 'User does not exit';
exit();
}
?>
I have tried using
header('Location: account');
and
window.location.href = "account";
after the session is saved but none is working, please who can help me on how to get this done
You should try this jQuery Code and PHP Code by replacing them in your code section, It will definitely work for you:
<script type="text/javascript">
function loginSubmitFormData() {
var loginemail = $("#loginemail").val();
var loginpassword = $("#loginpassword").val();
var source = $("#source").val();
$.post("authlogin.php", { loginemail: loginemail, loginpassword: loginpassword },
function(data) {
var data = jQuery.parseJSON( data );
console.log(data);
$('#loginresults').html(data.message);
if(data.redirect_url){
window.location.href = data.redirect_url;
}
$('#loginmyForm')[0].reset();
});
}
</script>
<?php
session_start();
include 'config/info.php';
// get the details from form
$email=$_POST['loginemail'];
$password = stripslashes($_REQUEST['loginpassword']);
$password = mysqli_real_escape_string($conn,$password);
$sql="SELECT * FROM user_info WHERE email='".$email."'";
$result = mysqli_query($conn,$sql);
$Countrow = mysqli_num_rows($result);
if ($Countrow == 1) {
$fetchrow = mysqli_fetch_assoc($result);
$loginpassword = $fetchrow['password'];
// Verify the password here
if (password_verify($password, $loginpassword)) {
$_SESSION['email'] = $email;
//setcookie('username', $adminID, time() + (86400 * 30), "/");
$date = date('Y-m-d H:i:s');
$ActivityStmt = "INSERT INTO login_activity (`email`, `last_login`, `browser`, `os`, `ip_address`) VALUES('".$email."', '".$date."', '".$gen_userBrowser."', '".$gen_userOS."', '".$gen_userIP."')";
$ActivityResult = mysqli_query($conn, $ActivityStmt);
$message = 'Login Successfully!';
$response = array(
'message' => $message,
'redirect_url' => 'https://www.example.com',
);
exit();
}
else{
$message = 'Incorrect Password';
$response = array(
'message' => $message
);
exit();
}
}
else{
$message = 'User does not exit';
$response = array(
'message' => $message,
);
exit();
}
echo json_encode( $response);
?>

Redirect to another page in PHP through AJAX

My page is gathering info from javascript and sending it to PHP and then to MySQL, issue is that i want it to redirect to different pages depending on the data i have in the DB, I've tried to use header but it just shows me the whole HTML code of the other page in the alert and I don't want that. I want it to redirect to one page or another depending on the condition
HTML (Login.html)
<div class="wrap-input100 validate-input" data-validate = "Enter username">
<input class="input100" type="text" id="user" name="username" placeholder="Email">
<span class="focus-input100" data-placeholder=""></span>
</div>
<div class="wrap-input100 validate-input" data-validate="Enter password">
<input class="input100" type="password" id="pass" name="pass" placeholder="Password">
<span class="focus-input100" data-placeholder=""></span>
</div>
<div class="container-login100-form-btn">
<a class="login100-form-btn" id = "logBtn">
Login
</a>
</div>
SCRIPT
$('#logBtn').click(function(event){
user = document.getElementById("user").value;
password = document.getElementById("pass").value;
$.ajax({
type:"POST",
url:"login.php",
async: false,
data: {user:user,password:password},
success: function(data){
alert(data);
//window.location = '../Main/index.html';
}
});
});
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "tbjdjkdl";
$dbname = "dbbbbbb";
$conn = new mysqli($servername, $username, $password, $dbname);
$user = $_POST['user'];
$pass = $_POST['password'];
$sql = "SELECT * FROM users WHERE email='$user' AND clave='$pass'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$sql = "SELECT * FROM users WHERE email='$user' AND clave='$pass' AND permisos='Administrador'";
if (mysqli_num_rows($result) > 0){
echo "admin";
header('Location: ../Main/index.html');
exit;
}
else{
echo "user";
header('Location: ../Main/startemp.html');
exit;
}
} else {
$msg = "username/password invalid";
echo $msg;
}
mysqli_close($conn);
?>
Use proper AJAX format to handle the response in client side here is the modified code
login.html
<div class="wrap-input100 validate-input" data-validate = "Enter username">
<input class="input100" type="text" id="user" name="username" placeholder="Email">
<span class="focus-input100" data-placeholder=""></span>
</div>
<div class="wrap-input100 validate-input" data-validate="Enter password">
<input class="input100" type="password" id="pass" name="pass" placeholder="Password">
<span class="focus-input100" data-placeholder=""></span>
</div>
<div class="container-login100-form-btn">
<a class="login100-form-btn" id = "logBtn">
Login
</a>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$('#logBtn').click(function(event){
user = document.getElementById("user").value;
password = document.getElementById("pass").value;
$.ajax({
type:"POST",
url:"login.php",
async: false,
data: {user:user,password:password},
success: function(data){
alert(data);
if(data=="admin"){
window.location="https://..Main/index.html";
}
if(data=="user"){
window.location="https://....startemp.html";
}
}
});
});
</script>
login.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
$user = $_POST['user'];
$pass = $_POST['password'];
$sql = "SELECT * FROM users WHERE email='$user' AND clave='$pass'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$sql_1 = "SELECT * FROM users WHERE email='$user' AND clave='$pass' AND permisos='Administrador'";
$result_1 = mysqli_query($conn, $sql_1);
if (mysqli_num_rows($result_1) > 0){
echo "admin";
exit(0);
}
else{
echo "user";
exit(0);
}
} else {
$msg = "username/password invalid";
echo $msg;
}
mysqli_close($conn);
?>
Use proper JSON format to handle the response in client side here is the modified code
<?php
$servername = "localhost";
$username = "root";
$password = "tbjdjkdl";
$dbname = "dbbbbbb";
$conn = new mysqli($servername, $username, $password, $dbname);
$user = $_POST['user'];
$pass = $_POST['password'];
$sql = "SELECT * FROM users WHERE email='$user' AND clave='$pass'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$sql = "SELECT * FROM users WHERE email='$user' AND clave='$pass' AND permisos='Administrador'";
if (mysqli_num_rows($result) > 0) {
echo json_encode(['status' => 'success', 'url' => '../Main/index.html']);
exit;
} else {
echo json_encode(['status' => 'success', 'url' => '../Main/startemp.html']);
exit;
}
} else {
$msg = "username/password invalid";
echo json_encode(['status' => 'error', 'msg' => $msg]);
}
mysqli_close($conn);
?>
Your JS
<script type="text/javascript">
$('#logBtn').click(function (event) {
user = document.getElementById("user").value;
password = document.getElementById("pass").value;
$.ajax({
type: "POST",
url: "login.php",
async: false,
data: {user: user, password: password},
success: function (data) {
if (data.status === 'success')
window.location.href = data.url; //Just do the redirection here
} else {
//Do your failiure stuff
}
}
});
});
</script>
You can use a JSON type of response to the Ajax Request so that the Ajax callback will handle the redirection.
SCRIPT
$('#logBtn').click(function(event){
user = document.getElementById("user").value;
password = document.getElementById("pass").value;
$.ajax({
type:"POST",
url:"login.php",
dataType: "JSON",
async: false,
data: {
user:user,
password:password
},
success: function(data){
alert(data.message);
alert(data.redirect);
window.location.href = data.redirect;
}
});
});
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "tbjdjkdl";
$dbname = "dbbbbbb";
$conn = new mysqli($servername, $username, $password, $dbname);
$user = $_POST['user'];
$pass = $_POST['password'];
$sql = "SELECT * FROM users WHERE email='$user' AND clave='$pass'";
$result = mysqli_query($conn, $sql);
$return = array();
if (mysqli_num_rows($result) > 0) {
$sql = "SELECT * FROM users WHERE email='$user' AND clave='$pass' AND permisos='Administrador'";
if (mysqli_num_rows($result) > 0){
$return = array(
"message" => "admin",
"redirect" => "../Main/index.html";
);
}
else{
$return = array(
"message" => "user",
"redirect" => "../Main/startemp.html";
);
}
} else {
$return = array(
"message" => "username/password invalid",
"redirect" => "";
);
}
echo json_encode($return);
mysqli_close($conn);
exit;
?>
$('#logBtn').click(function(event){
user = document.getElementById("user").value;
password = document.getElementById("pass").value;
$.ajax({
type:"POST",
url:"login.php",
async: false,
data: {user:user,password:password},
success: function(data){
if(data == 'admin'){
window.location.href='../Main/index.html';
}
elseif(data == 'user'){
window.location.href='../Main/startemp.html';
}else{
alert(data);
}
});
});
//please remove the line header() on login.php;

How to retrieve PHP column value into Javascript for login validation?

I am writing a simple login validation. (I know people say I shouldn't deal with passwords in plaintext, because it's dangerous, however, I am doing this for a school assignment where we do not need to use any security.) The issue I am having here is that I can't get the message for login to be successful. I am getting a login failure. I inserted a couple of users and passwords into a database table. What I need to do is to get the value from the "name" column and the "pwd" (password) column from my database table and allow a successful login (in Javascript) if the user's input has a match with the user and password in the database table.
Here is my form code:
<form method="post" action="login.php" onsubmit="validateForm()" id="loginForm" name="loginForm">
Name:<br>
<input type="text" name="personName"><br>
Password:<br>
<input type="password" name="pswd"><br>
<input type="submit" name="submit" id="submit" value="Login" />
</form>
Javascript:
<script>
function validateForm()
{
var n = document.loginForm.personName.value;
var p = document.loginForm.pswd.value;
//The var below is what I need help on.
var name = "<?php echo $row['name']; ?>";
//The var below is what I need help on.
var ps = "<?php echo $row['pwd']; ?>";
if ((n == name) && (p == ps))
{
alert ("Login successful!");
return true;
}
else
{
alert ("Login failed! Username or password is incorrect!");
return false;
}
}
</script>
PHP code (I have an empty while statement just in case I need it):
<?php
function validateLogin()
{
//I hid this information from here.
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$dbc = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($dbc->connect_error)
{
die("Connection failed: " . $dbc->connect_error);
}
$n = $_POST["personName"];
$p = $_POST["pswd"];
$query = "SELECT `name`, `pwd` FROM `chatApp`";
$result = $dbc->query($query);
$numRows = mysql_num_rows($result);
$count = 1;
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
}
}
else
{
echo "0 results";
}
$dbc->close();
}
if(array_key_exists('loginForm',$_POST))
{
validateLogin();
}
?>

PHP Registration Form not processing AJAX data

I may be being stupid, but I am trying to process a registration form using an AJAX call to a PHP page. My PHP page is working perfectly on it's own, but when I try to post the form data to the PHP page through AJAX nothing happens.
This is my AJAX call:
$(document).ready(function ($) {
$("#register").submit(function(event) {
event.preventDefault();
$("#message").html('');
var values = $(this).serialize();
$.ajax({
url: "http://cs11ke.icsnewmedia.net/DVPrototype/external-data/register.php",
type: "post",
data: values,
success: function (data) {
$("#message").html(data);
}
});
});
});
This is the form:
<div id="registerform">
<form method='post' id='register'>
<h3>Register</h3>
<p>Fill in your chosen details below to register for an account</p>
<p>Username: <input type='text' name='username' value='' /><br />
Password: <input type='password' name='password' ><br />
Repeat Password: <input type='password' name='repeatpassword'></p>
<input name='submit' type='submit' value='Register' >
<input name='reset' type='reset' value='Reset'><br /><br />
</form>
<div id="message"></div>
</div>
And this is my PHP page:
<?php function clean_string($db_server = null, $string){
$string = trim($string);
$string = utf8_decode($string);
$string = str_replace("#", "&#35", $string);
$string = str_replace("%", "&#37", $string);
if (mysqli_real_escape_string($db_server, $string)) {
$string = mysqli_real_escape_string($db_server, $string);
}
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return htmlentities($string);
}
function salt($string){
$salt1 = 'by*';
$salt2 = 'k/z';
$salted = md5("$salt1$string$salt2");
return $salted;
}
?>
<?php
//form data
$submit = trim($_POST['submit']);
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$repeatpassword = trim($_POST['repeatpassword']);
// create variables
$message = '';
$s_username = '';
//connect to database
{databaseconnection}
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
if(!$db_server){
//error message
$message = "Error: could not connect to the database.";
}else{
$submit = clean_string($db_server, $_POST['submit']);
$username = clean_string($db_server, $_POST['username']);
$password = clean_string($db_server, $_POST['password']);
$repeatpassword = clean_string($db_server, $_POST['repeatpassword']);
//check all details are entered
if ($username&&$password&&$repeatpassword){
//check password and repeat match
if ($password==$repeatpassword){
//check username is correct length
if (strlen($username)>25) {
$message = "Username is too long, please try again.";
}else{
if (strlen($password)>25||strlen($password)<6) {
//check password is correct length
$message = "Password must be 6-25 characters long, please try again.";
}else{
mysqli_select_db($db_server, $db_database);
// check whether username exists
$query="SELECT username FROM users WHERE username='$username'";
$result= mysqli_query($db_server, $query);
if ($row = mysqli_fetch_array($result)){
$message = "Username already exists. Please try again.";
}else{
//insert password
$password = salt($password);
$query = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
mysqli_query($db_server, $query) or die("Registration failed. ".
mysqli_error($db_server));
$message = "Registration successful!";
}
}
}
}else{
$message = "Both password fields must match, please try again.";
}
}else{
$message = "You must fill in all fields, please try again.";
}
}
echo $message;
mysqli_close($db_server);
?>
Apologies for all the code. I feel I may be making a stupid mistake but I don't know why the data isn't being posted or returned.
Thanks in advance!
Notice: This is more a comment than an answer but this is more readable since it includes code.
== EDIT ==
I Checked your code on http://cs11ke.icsnewmedia.net/DVPrototype/#registerlogin, your form doesn't have a id assigned to it
First: use your console...do you see an XMLHTTPREQUEST in your console?
What are the responses/headers etc? I can't stress this enough: use your console and report back here!!!
Next up the overly complicated ajax call...dumb it down to:
$('#register').submit(function(){
$('#message').html('');
$.post("http://cs11ke.icsnewmedia.net/DVPrototype/external-data/register.php",
$(this).serialize(),
function(response){
console.log(response);
$('#message').html(response);
}
);
return false;
});
In your PHP put this on top to check whether anything at all came through:
die(json_encode($_POST));
Please use Firebug or any other tool, to checḱ if the AJAX-script is called, what is its answer and if there are any errors in the script
My form is not submitting data to my database.
This is the PHP code:
<?php require 'core.inc.php'; ?>
<?php require 'connection.inc.php'; ?>
<?php
if(isset($_POST['username']) && isset($_POST['password']) &&
isset($_POST['password_again']) && isset($_POST['firstname']) &&
isset($_POST['surname'])){
$username = $_POST['username'];
$password = $_POST['password'];
$hashed_password = sha1($password);
$password_again = sha1('password again');
$username = $_POST['firstname'];
$password = $_POST['surname'];
//check if all fields have been filled
if(!empty($username)&& !empty($password) && !empty($password_again) &&
!empty($firstname)&& !empty($surname)){
if($password != $password_again){
echo 'Passwords do not match.';
} else {
//check if user is already registered;
$query = "SELECT username FROM user WHERE username = {$username} ";
$query_run = mysqli_query($connection, $query);
if (mysqli_num_rows ($query_run)==1){
echo 'User Name '.$username.' already exists.';
} else {
//register user
$query = "INSERT INTO `user` VALUES ('', '".$username."',
'".$password_hashed."','".$firstname."','".$surname."',)";
}
if($query_run = mysqli_query($connection, $query)){
header('Location: reg_succed.php');
} else {
echo 'Sorry we couldn\'t register you at this time. try again later';
}
}
}
} else {
echo 'All fields are required';
}
?>
<h2>Create New User</h2>
<form id="form" action="<?php echo $current_file ?>" method="POST">
<fieldset title="Login details" id="frame">
<legend>USER LOGIN DETAILS</legend>
<label>User Name:</label><br/>
<input type="text" name = "username" id = "username" value="<?php if(isset($username)){ echo $username; } ?>" maxlength="50" placeholder="Enter your Username" required/><br/>
<label>First Name:</label><br/>
<input type="text" name="firstname" id = "firstname" value="<?php if(isset($firstname)){ echo $firstname;} ?>" maxlength="50" placeholder="Enter your Firstname" required/><br/>
<label>Surname:</label><br/>
<input type="text" name="surname" id="surname" value="<?php if(isset($surname)) {echo $surname;} ?>" maxlength="50" placeholder="Enter your Surname" required/><br/>
<label>Password:</label><br/>
<input type="password" name="password" id="password" maxlength="50" placeholder="Enter your Password" required/><br/>
<label>Password Again:</label><br/>
<input type="password" name="password_again" id="password again" maxlength="50" placeholder="Enter your Password" required/><br/>
<input type="submit" name = "register" id = "register" value="Register">
</fieldset>
</form>
connection code
<?php
require_once("constants.php");
// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS, DB_NAME);
if (!$connection) {
die("Database connection failed: " . mysqli_error($connection));
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
?>
core.inc.php code
<?php
ob_start();
session_start();
$current_file = $_SERVER['SCRIPT_NAME'];
if(isset( $_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])){
$http_referer = $_SERVER['HTTP_REFERER'];
}
?>

Creating update user profile page using PHP MySql

I have managed to go ahead with my user update page and it all seems to be fine at the form I had it reading the current details from logged in user when i clicked submit it says submit successful, then I am stuck with this page can't go back, I don't know if it worked and cannot see any error messages or any that i can see.
I am very new to coding so sorry if any silly mistake i missed out on... someone help me please....
Here is my PHP
<?php
include_once("php_includes/check_login_status.php");
session_start();
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
}
else {
echo "You have not signed in";
}
// Initialize any variables that the page might echo
$firstname = "";
$surname = "";
$u = "";
$weight = "";
$height = "";
// Make sure the _GET username is set, and sanitize it
if(isset($_GET["u"])){
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
} else {
header("location: index.php");
exit();
}
// Select the member from the users database table
$sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// check if the user exists in the database
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "That user does not exist or is not yet activated, press back";
exit();
}
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$firstname = $row["firstname"];
$surname = $row["surname"];
$weight = $row["weight"];
$height = $row["height"];
$profile_id = $row["id"];
$u = $row["u"];
}
// this is the calculation of the BMI index
//$BMI = ($weighteight / ($heighteight * $heighteight))* 10000;
if($firstname =="" || $surname == ""|| $weight == "" || $height == ""){
echo "The form submission is missing values.";
exit();
} else {
$p_hash = md5($p);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (firstname, surname, weight, height)
VALUES('$fn','$sn','$w','$h')";
$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 = "k1003140#kingston.ac.uk";
$subject = 'studentnet.kingston.ac.uk/k1003140';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>yoursitename 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.yoursitename.com/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">yoursitename 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 />* E-mail Address: <b>'.$e.'</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();
?>
Here is my Javascript code
<script>
function signup(){
var u = _("username").value;
var fn = _("firstname").value;
var sn = _("surname").value;
var w = _("weight").value;
var h = _("height").value;
var e = _("email"). value;
var status = _("status");
if(fn == "" || sn == "" || w == "" || h == ""|| g == ""){
status.innerHTML = "Fill out all of the form data";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.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("fn="+fn+"&sn="+sn+"&w="+w+"&h="+h+);
}
}
here i added some more of my code to see the HTML
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
<form name="signupform" id="signupform" onsubmit="return false;">
<div id="usernamecss"><?php echo $u; ?></div>
<p><b>Is the viewer the page owner, logged in and verified? <?php echo $isOwner; ?></b></p>
<p>First Name: <input type="text" name="firstname" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$firstname?>'></p>
<p>Surname: <input type="text" name="surname" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$surname?>'></p>
<p>Weight: <input type="text" name="weight" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$weighteight?>'></p>
<p>Height: <input type="text" name="height" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$heighteight?>'></p>
<button id="signupbtn" onclick="signup()">Create Account</button>
</div>
</form>
<?php include_once("template_pageBottom.php"); ?>
<span id="status"></span>
</body>
i can't write comment so i will write here
U should use session_start(); at the first line of the page and this may cause some problem try it
session_start();
include_once("php_includes/check_login_status.php");
As I can see you are doing a POST in your ajax but are reacting to GET in your php.
Try to change:
if(isset($_GET["u"])){
to:
if(isset($_POST["u"])){
or:
if(isset($_REQUEST["u"])){

Categories