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"])){
Related
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();
}
?>
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());
}
}
}
?>
Im creating login script which are based on javascript and PHP. But I had problem with it.
Whatever I send via form I will be redirected to user.php?u=loginfailed. It doesen't matter whether it is properly email and password (which I have in my database). As you can see page "user.php?u=X" should be open only when email and password are entered correctly. But in my case when I sent correct data and incorrect data it will be the same... To sum up - correct data should redirected me to user.php?u=X and incorrect should display an error message below the form.
What do you think about it?
Index.php
<?php
if(isset($_POST["e"])){
include_once("../db/db_fns.php");
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = md5($_POST['p']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
if($e == "" || $p == ""){
echo "loginfailed";
exit();
} else {
$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 "loginfailed";
exit();
} else {
$_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);
$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();
}
?>
<script src="../js/main.js"></script>
<script src="../js/ajax.js"></script>
<script src="login.js"></script>
<form id="loginform" onsubmit="return false;">
<div>Email Address:</div>
<input type="text" id="email" onfocus="emptyElement('status')" maxlength="88">
<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.js
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", "index.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "loginfailed") {
_("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);
}
}
Try this :
Try to alert ajax.responseText and see if it return proper result without an error. Also user trim before comparing responsetext like this : if(ajax.responseText.trim() == "loginfailed")
Why you are not using Jquery as it is very simple and easy to use.
I believe you are missing return and therefore your form is submitting regardless. Don't forget to have the login() function return false so it doesn't submit.
try <button id="loginbtn" onclick="return login();">Log In</button>
So I've got this form where users signs his ass up. When the user filled in all the details, he clicks on the submit button. An Ajax request submits the form and puts all the details in the database. If that has happen without any errors, a hidden div with two (payments) buttons opens up. After clicking on the iDeal or PayPal button, colorbox opens up and show the 'overview-page'. Now I'd like to show the users information from the database via $_SESSION['user_id']. But somehow, I'm not storing the session orso as the 'overview-page' is empty.
I'm not sure what I'm missing, any heads up would be awesome!
This is the form:
<div class="content main container" id="goShowOrderForm">
<div class="content main box">
<div id="udidOrderForm" class="order form">
<form action="post" id="orderForm" name="form">
<label for="email">Email</label>
<input type="email" class="input-fullwidth" name="email">
<div class="two-column">
<label for="password">Password</label>
<input type="password" name="password">
</div>
<div class="two-column right">
<label for="repassword">Confirm Password</label>
<input type="password" name="re_password">
</div>
<input type="hidden" name="token" value="<?php echo $_SESSION['guest_token'] ?>">
</form>
<div class="orderFormActions">
<input type="submit" class="button darkblue order" name="submitNewStep" id="submitNewStep" value="Nu afrekenen">
<div class="button red cancel" id="cancelUdidOrder">Afbreken</div>
</div>
</div>
</div>
Ajax post page (to store data in db after submit)
<?php
include '../includes/database/db_connect.php';
include '../includes/database/functions.php';
if($_POST) {
//Form data
$email = safe($mysqli,$_POST['email']);
$guestToken = safe($mysqli,$_POST['token']);
$password = veilig($mysqli,$_POST['password']);
$rePassword = veilig($mysqli,$_POST['re_password']);
//Check if everything has been filled in correctly
if ($email == '' || $password == '' || $rePassword == '') {
echo "orderFormRequiredFields";
exit();
}
//Check emailFormat
if (!CheckEmailFormat($email)) {
echo "orderFormerrorEmailFormat";
exit();
}
//Check if email already exist
$checkIfEmailExist = mysqli_query($mysqli,"SELECT * FROM members WHERE email = '$email'");
if (mysqli_num_rows($checkIfEmailExist) > 0){
echo "orderFormEmailAlreadyExist";
exit();
}
//Check if the two passwords do match
if ( $password == $rePassword ) {
//Als wachtwoorden overeen komen, maak er een hashed pw + salt van
$salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
$saltedPW = $password . $salt;
$hashedPW = hash('sha256', $saltedPW);
} else {
echo "orderFormErrorPasswordConfirm";
exit();
}
$tstamp = time();
$token = md5(uniqid(mt_rand()));
//Add user to the database
$createUser = mysqli_query($mysqli,"INSERT INTO members (account_active, email, guest_token, password, salt)
VALUES ('0', '$email', '$guestToken', '$hashedPW', '$salt'); ");
//begin storing user_id
//Check for the users salt
$getSalt = mysqli_query($mysqli,"SELECT salt FROM members WHERE email = '$email';");
if (!$getSalt) {
echo "Error Salt";
exit();
}
$row = mysqli_fetch_assoc($getSalt);
$salt = $row['salt'];
//Find the user details
$saltedPW = $password . $salt;
$hashedPW = hash('sha256', $saltedPW);
$findUser = mysqli_query($mysqli,"SELECT * FROM members WHERE email = '$email' AND password = '$hashedPW'");
$roww = mysqli_fetch_assoc($findUser);
$user_id = $roww['user_id'];
//If users exist, count should be 1
$count = mysqli_num_rows($findUser);
if($count == 1) {
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = $email;
} else {
echo "Error";
exit();
}
//end
echo "succesMsgOrderForm";
}
?>
This is the basic of the overview page
<?php
include 'includes/database/db_connect.php';
include 'includes/database/functions.php';
sec_session_start();
$user_id = $_SESSION['user_id'];
$getAllDetails = mysqli_query($mysqli,"SELECT * FROM members WHERE user_id = '$user_id' ") OR die (mysqli_error($mysqli));
$row = mysqli_fetch_array($getAllDetails);
$email = $row['email'];
?>
<body>
user_id is: <?php echo $user_id ?> <br>
email is: <?php echo $email ?>
</body>
Thank you,
Edit #1 sec_session_start() part which is in functions.php:
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = SECURE;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
ini_set('session.use_only_cookies', 1);
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(); // regenerated the session, delete the old one.
}
Edit #2 - Part where I open up the colorbox (javascript)
$(document).on('click', '#pay_ideal', function(){
$.colorbox({
width: 500,
height: 350,
speed: 350,
closeButton: false,
href:"order-overview.php"
});
});
You need to check session status before refreshing your session lik;
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = SECURE;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
ini_set('session.use_only_cookies', 1);
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
if (session_id() == '') {
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id();
}
}
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("#", "#", $string);
$string = str_replace("%", "%", $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'];
}
?>