Checking if username is available before submitting a form - javascript

I want to check if the username is taken before the form is submitted.
As far as I can understand I have to use AJAX to get data from my database in javascript. How do I send the username to the PHP file?
This is my form:
<form id="loginForm" action="register.php" method="post">
<p>Register:</p>
<p style="text-align: left;">Full name: <br><input type="text" name="name" required/></p>
<p style="text-align: left;">Email: <br><input type="text" name="email" required/></p>
//Username
<p style="text-align: left;">Username: <br><input id="username" type="text" name="username" onkeyup="validateUsername(value);" required/></p>
<span id="usernameError" style="display:none;border:1px solid red;">Username can only contain a-z, 0-9 and must be at least 6 characters loong</span>
<span id="usernameTaken" style="display:none;border:1px solid red;">Username taken</span>
<p style="text-align: left;">Password: <br><input type="password" name="password" required/></p>
<input type="submit" value="Register">
</form>
This is the validateUsername() function:
function validateUsername(username) {
var re = /[a-zA-Z0-9]/;
alert(username.length);
if(re.test(username) && username.length > 5) {
document.getElementById('username').style.backgroundColor = "green";
document.getElementById('usernameError').style.display= "none";
--error;
} else {
document.getElementById('username').style.backgroundColor = "red";
document.getElementById('usernameError').style.display= "block";
++error;
}
//here i want to check if the user name is taken
}
If the username is taken, I want to display the 'usernameTaken' span.
Otherwise, I want to hide it.
Here is the PHP file that checks if the username is already in the database:
<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'MyPassword');
define('DB_HOST', 'mysql43.unoeuro.com');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' .mysqli_error());
}
$db_selected = mysqli_select_db( $link, DB_NAME);
if (!$db_selected) {
die('Could not connect: ' .mysqli_connect_error());
}
$username = //The username;
$username = mysqli_real_escape_string($link,$username);
$sql = "SELECT * FROM mainLogin WHERE username = '$username'";
$result = mysqli_query($link, $sql);
$count = mysqli_num_rows($result);
if($count == 0) {
//if the username is NOT taken
return true;
} else {
//if the username IS taken
return false;
}
mysqli_close($link);
?>
How is this done?

JS - JQUERY AJAX
$.ajax({
url: 'register.php', data: {action: 'isUserNameTaken', params: [username]},
type: 'post',
success: function(data) {
//Do Something
}
});
PHP
<?php
function isUserNameTaken($username) {
//Do Something;
}
if(!empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'isUserNameTaken':
$username = '';
if(!empty($_POST['params'])) {
$username = $_POST['params'][0];
}
isUserNameTaken($username);
break;
}
}
?>

You could do it this way:
On client side:
function validateUsername(){
if(//test username input for length...) {
$.ajax({
type: 'POST',
url: 'validate.php',
data: { username: username },
success: function(response) {
if(response==0){
//username is valid
}
elseif(response==1){
//username is already taken
}
elseif(response==2){
//connection failed
}
}
});
}
else{
//display "username is too short" error
}
}
validate.php:
<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'MyPassword');
define('DB_HOST', 'mysql43.unoeuro.com');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' .mysqli_error());
echo json_encode(2);
}
else{
$db_selected = mysqli_select_db( $link, DB_NAME);
if (!$db_selected) {
die('Could not connect: ' .mysqli_connect_error());
echo json_encode(2);
}
else{
$username = $_POST["username"];
$username = mysqli_real_escape_string($link,$username);
$sql = "SELECT * FROM mainLogin WHERE username = '$username'";
$result = mysqli_query($link, $sql);
$count = mysqli_num_rows($result);
if($count == 0) {
//if the username is NOT taken
echo json_encode(0);
}else {
//if the username IS taken
echo json_encode(1);
}
mysqli_close($link);
}
}
?>
You can also make this function validateUsername by calling it with onkeyup function in jquery so every time a user types something into the input field, the username will be checked....

Related

How to autofill city name by giving pin code using javascript and php?

I am not able to autofill city by giving pincode even though database connection successfull.
Below is the code:
pin.php
<body>
<form>
<label >Pincode </label>
<input type="text" class="form-control" placeholder="Enter Pin Code" name="pin_value" id="pin" maxlength="6" pattern=".{6,6}" title="Exacty 6 digits" onkeypress="return isNumberKey(event)" onkeypress="set_city()" required="">
<label >City </label>
<input type="text" class="form-control" placeholder="Enter City" name="city_value" id="city" onkeypress="return isCharacterKey(event)" >
<?php
include("configs.php");
$pin = $_POST['pin'];
$query = $conn->query("SELECT cityname FROM pincodes WHERE pincode = '$pin'");
while($row = $query->fetch_assoc()) {
?>
<option> <?php echo $row["cityname"];?></option>
<?php
}?>
</form>
<script>
function set_city(){
var pin = document.getElementById("pin").value;
$.ajax({
url: "load_pincode.php",
method: "post",
data: {pin: pin},
success: function(response){
if(response == ""){
alert("please enter pincode");
}
else{
$("#city").val(response);
}
}
});
}
</script>
</body>
load_pincode.php
<?php
#ob_start();
session_start();
include("configs.php");
$pin = $_POST['pin'];
if($_POST["pin"])
{
$uid = $_SESSION['user_id'];
$user_type = $_SESSION["user_type"];
if($user_type=="lite"){
$cur_uid = $uid;
$uid = $_SESSION["ad_id"];
}
$cur_bid = $_SESSION["default_business_id"];
$q = $conn->query("SELECT user_pin FROM business WHERE year = '$curr_year' AND user_id = '$uid' AND business_id = '$cur_bid'");
$c;
while($r=$q->fetch_assoc()){
$c = $r["user_pin"];
}
$qg = $conn->query("SELECT cityname FROM pincodes WHERE pincode = '$pin' ");
while($rg = $qg->fetch_assoc()) {
$p = $rg["cityname"];
}
}else{
echo "prob";
}
?>
Its neither displaying error nor output.I am stuck in this auto-filling not able to move further.
How will I get to know whether it is passing value of pin to load_pincode.php ?
I am not going through your whole code but
First of all you are getting the value of city name according to the pincode but not returning it ,
$qg = $conn->query("SELECT cityname FROM pincodes WHERE pincode = '$pin' ");
while($rg = $qg->fetch_assoc()) {
$p = $rg["cityname"];
}
echo json_encode($p); // here getting the city name
You need to return json array of the result and modify the ajax script to display the city. Please see below.
load_pincode.php
<?php
#ob_start();
session_start();
include("configs.php");
$pin = $_POST['pin'];
if($_POST["pin"])
{
$uid = $_SESSION['user_id'];
$user_type = $_SESSION["user_type"];
if($user_type=="lite"){
$cur_uid = $uid;
$uid = $_SESSION["ad_id"];
}
$cur_bid = $_SESSION["default_business_id"];
$q = $conn->query("SELECT user_pin FROM business WHERE year = '$curr_year' AND user_id = '$uid' AND business_id = '$cur_bid'");
$c;
while($r=$q->fetch_assoc()){
$c = $r["user_pin"];
}
$qg = $conn->query("SELECT cityname FROM pincodes WHERE pincode = '$pin' ");
while($rg = $qg->fetch_assoc()) {
$p = $rg["cityname"];
}
echo json_encode(array('city' => $p)); exit();
}else{
echo "prob";
}
?>
-------------------------------------------------
$.ajax({
url: "load_pincode.php",
method: "post",
data: {pin: pin},
success: function(response){
if(response == ""){
alert("please enter pincode");
}
else{
$("#city").val(response.city);
}
}
});

Email Live Checking PHP and Mysql

I have an issue im stuck for 3 days. Im trying to check in DB if the email the user is entering is already registered and avoid registering in duplicate. But this doesn't seem to work fine
here is my code:
This is in the HTML
<script type="text/javascript">
$(document).ready(function() {
$("#cf_email").keyup(function(e) {
var uname = $(this).val();
if (uname == "")
{
$("#msg").html("");
$("#Submit").attr("disabled", true);
}
else
{
$("#msg").html("Verificando, espere...");
$.ajax({
url: "check_availability.php",
data: {Email: uname},
type: "POST",
success: function(data) {
if(data.status == true) {
$("#msg").html('<span class="text-danger">Email ya registrado!</span>');
$("#Submit").attr("disabled", true);
} else {
$("#msg").html('<span class="text-success">Email Disponible para Registrar!</span>');
$("#Submit").attr("disabled", false);
}
}
});
}
});
});
</script>
<right><form id="register" action="contact.php" method="post">
<p><label>E-mail para Registro</label></p>
<input type="text" name="cf_email" id="cf_email" title="Email" class="demoInputBox" placeholder="Email Valido" required><div id="msg" class="form-group"></div>
</form></right>
this is the check_availability.php
$con = mysqli_connect($host, $user, $pass, $db) or die("Error " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (isset($_POST["cf_email"]) && $_POST['cf_email'] != '')
{
$response = array();
$cfmail = mysqli_real_escape_string($con,$_POST['cf_email']);
$sql = "select Email from Bares where Email='".$cfmail."'";
$res = mysqli_query($con, $sql);
$count = mysqli_num_rows($res);
if($count > 0)
{
$response['status'] = false;
$response['msg'] = 'email already exists.';
}
else
{
$response['status'] = true;
$response['msg'] = 'email is available.';
}
echo json_encode($response);
}
?>
it doesn't matter which email i introduce in the textfield because always says its available even if the email is registered already in the database
In your JS you're processing a string, not an object. You need to parse it:
success: function(data) {
dataObj = JSON.parse(data);
if(dataObj.status == true) {
....
This is an Example with mysqli OOP try it will work without Problem:
PHP:
<?php $mysqli=new mysqli($host, $user, $pass, $db); mysqli_set_charset($mysqli,'utf8');
if (!empty($_POST['cf_email'])){
extract($_POST);
$sql=$mysqli->query("select Email from Bares where Email='".$cf_email."'");
if($sql->num_row>0){
$status=1;
}
else{
$status=0;
}
echo $status;
die;}
?>
HTML:
<right>
<form id="register" action="contact.php" method="post">
<p><label>E-mail para Registro</label></p>
<input type="text" name="cf_email" id="cf_email" title="Email" class="demoInputBox" placeholder="Email Valido" required>
<input type="submit" id="submit">
<div id="msg" class="form-group"></div>
</form>
</right>
JS:
<script type="text/javascript">
$(document).ready(function() {
$("#cf_email").keyup(function(e) {
var uname = $(this).val();
if (uname == "") {
$("#msg").html("");
$("#submit").attr('disabled', true);
} else {
$.ajax({
url: "check_availability.php",
data: $(this).serialize(),
type: "POST",
success: function(data) {
if (data == 1) {
$("#msg").html('<span class="text-danger">Email ya registrado!</span>');
$("#submit").attr('disabled', true);
} else {
$("#msg").html('<span class="text-success">Email Disponible para Registrar!</span>');
$("#submit").attr('disabled', false);
}
}
});
}
});
});
</script>

Php form data not submitting on mysql databse with username check

The form is loading on the registration page. But after giving any input it's not storing on MySQL database plus it also doesn't check for username availability.
Here is HTML code part:
<html>
<link type="text/css" rel="stylesheet" href="design.css">
<div class ="cus_head"> </div>
<body>
<center> <h1 style="color:#1AAB30;">Register </h1>
<form method="post" action="reg_process.php">
UserName: <input type="text" name="cus_username" >
<span class="error">* <?php echo $cus_username_err;?></span>
<span id="username_status"></span>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/users.js"></script>
<br><br>
First Name: <input type="text" name="firstname">
<span class="error">* <?php echo $firstname_err;?></span>
<br><br>
Last Name: <input type="text" name="lastname">
<span class="error">* <?php echo $lastname_err;?></span>
<br><br>
Email Id: <input type="email" name="email">
<span class="error">* <?php echo $email_err;?></span>
<br><br>
Password: <input type="password" name="password">
<span class="error">* <?php echo $password_err;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</center>
</body>
<div class ="cus_head"> </div>
Here is the Javascript file code for username availability: users.js
$('#username').keyup( function() {
var username = $(this).val();
$('#username_status').text('Searching...');
if(username !== '') {
$.post('php/username_check.php', { username: username}, function(data) {
$('#username_status').text(data);
});
}
else {
$('#username_status').text('');
}
});
Here is the PHP Part: register.php
<?php
$link = mysqli_connect("%", "****", "****", "****");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
require 'username_check.php';
// define variables and set to empty values
$cus_username = $firstname = $lastname = $email = $password = "";
// defining variable and set to empty value for error
$cus_username_err = $firstname_err = $lastname_err = $email_err = $password_err = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['cus_username'])) {
$cus_username_err = "UserName is required";
} else {
$cus_username = sanitize($_POST['cus_username']);
}
if (empty($_POST['firstname'])) {
$firstname_err = "First Name is required";
} else {
$firstname = sanitize($_POST['firstname']);
}
if (empty($_POST['lastname'])) {
$lastname_err = "Last Name is required";
} else {
$lastname = sanitize($_POST['lastname']);
}
if (empty($_POST['email'])) {
$email_err = "Email is required";
} else {
$email = sanitize($_POST['email']);
}
if (empty($_POST['password'])) {
$password_err = "password is required";
} else {
$password = sanitize($_POST['password']);
}
}
// attempt insert query execution
$sql = "INSERT INTO ***** (`cus_username`, `firstname`, `lastname`, `email`, `password`) VALUES ('$cus_username', '$firstname', '$lastname','$email,'$password')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
function sanitize($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
mysqli_close($link);
?>
Here is the username_check.php
<?php
$link = mysqli_connect("%", "****", "*****", "*****");
if (isset($_POST['username']))
{
$username = sanitize($_POST['username']);
if (!empty($cus_username))
{
$sql = "SELECT *FROM ***** WHERE username = '$username'";
$count=mysqli_num_rows( $sql);
if($count==0)
{
echo "Username doesn't exist";
exit;
}
else
{
echo "Username already exists";
exit;
}
}
}
function sanitize($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
With reference to your username check script - as the ajax function is being triggered on keyup it is not likely that the entire field has been completed so using a like operator in the sql makes more sense.
Rather than directly embedding a variable in the sql statement it is a far better option to use prepared statements - the statement here uses a questionmark as a placeholder which is later bound to a constructed string variable containing the contents of $_POST['username'] at the time of the keyup
<?php
/*
username_check.php
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['username'] ) ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$rows=0;
/*
sql prepared statement using `LIKE` operator
*/
$sql='select * from `TABLE` where `username` like ?';
$stmt = $db->prepare( $sql );
if( $stmt ){
/* Bind the placeholder to an as yet undefined variable - $username */
$stmt->bind_param( 's', $username );
/* Generate the $username variable with trailing % */
$username = $_POST['username']."%";
/* Query the db */
$result = $stmt->execute();
if( $result ){
/* If the query succeeded, get the row count */
$stmt->store_result();
$rows=$stmt->num_rows;
}
/* tidy up */
$stmt->free_result();
$stmt->close();
}
$db->close();
/* Send response back to javascript callback */
exit( $rows > 0 ? "Username already exists" : "Username doesn't exist" );
}
?>
For the register.php script - again using prepared statements to avoid sql injection. Neither script is tested - they are for your guidance on how you might accomplish your goals
<?php
/*
register.php
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['cus_username'], $_POST['firstname'], $_POST['lastname'], $_POST['email'], $_POST['password'] ) ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql = 'insert into `TABLE` (`cus_username`, `firstname`, `lastname`, `email`, `password`) values (?,?,?,?,?);';
$stmt = $db->prepare( $sql );
if( $stmt ){
$username=!empty($_POST['cus_username']) ? $_POST['cus_username'] : false;
$firstname=!empty($_POST['firstname']) ? $_POST['firstname'] : false;
$lastname=!empty($_POST['lastname']) ? $_POST['lastname'] : false;
$email=!empty($_POST['email']) ? $_POST['email'] : false;
$password=!empty($_POST['password']) ? $_POST['password'] : false;
$errors=array();
if( !$username )$errors[]='Please enter a username';
if( !$password )$errors[]='Please enter your password';
if( !$email )$errors[]='Please enter your email';
if( !$firstname )$errors[]='Your firstname is required';
if( !$lastname )$errors[]='Your lastname is required';
if( empty( $errors ) ){
/* bind the variables and execute the sql statement */
$stmt->bind_param('sssss',$username,$firstname,$lastname,$email,$password);
$result = $stmt->execute();
echo $result ? 'Success' : 'Failed';
} else {
foreach( $errors as $error ){
echo $error . '<br />';
}
}
$stmt->close();
$db->close();
}
}
?>
-- Updates
The html/php page to add a new user
<?php
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Add a user</title>
<script src='//code.jquery.com/jquery-latest.js' type='text/javascript'></script>
<style>
html, html *{font-family:calibri,verdana,arial;font-size:0.85rem;}
label{clear:both;margin:0.25rem;padding:0.25rem;display:block;width:30%;float:left;}
input[type='submit']{margin:3rem 0;background:green;color:white;clear:both;float:left;}
input[type='text'],
input[type='email'],
input[type='password']{float:right;}
#username_status{color:red;margin:0 0 0 2rem;}
</style>
</head>
<body>
<h1>Register</h1>
<form method='post' action='reg_process.php'>
<!-- the text field needs an id for the ajax function to glom onto -->
<label for='cus_username'>UserName: <input type='text' name='cus_username' id='username' /><span id='username_status'></span></label>
<label for='firstname'>First Name: <input type='text' name='firstname' /></label>
<label for='lastname'>Last Name: <input type='text' name='lastname' /></label>
<label for='email'>Email Id: <input type='email' name='email' /></label>
<label for='password'>Password: <input type='password' name='password' /></label>
<!--
various spans removed for testing
and slight rearrangement using `label`
-->
<input type='submit' />
</form>
<!--
rather than sending an ajax request with each character typed
I updated this to check for a minimal length before sending the
request and also changed the event listener to listen for blur events
so there should only be one request when the user moves to the next
field in the form
-->
<script type='text/javascript'>
$('#username').blur( function(e) {
var status=$('#username_status');
status.text( 'Searching...' );
if( $( this ).val() !== '' && $( this ).val().length > 3 ) {
$.post('php/username_check.php', { username: $(this).val() }, function(data) {
status.text( data );
});
} else {
status.text('');
}
});
</script>
</body>
</html>
<?php
/*
username_check.php
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['username'] ) ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$rows=0;
/*
sql prepared statement using `LIKE` operator
*/
$sql='select * from `users` where `username` like ?';
$stmt = $db->prepare( $sql );
if( $stmt ){
/* Bind the placeholder to an as yet undefined variable - $username */
$stmt->bind_param( 's', $username );
/* Generate the $username variable with trailing % */
$username = $_POST['username']."%";
/* Query the db */
$result = $stmt->execute();
if( $result ){
/* If the query succeeded, get the row count */
$stmt->store_result();
$rows=$stmt->num_rows;
}
/* tidy up */
$stmt->free_result();
$stmt->close();
}
$db->close();
/* Send response back to javascript callback */
exit( $rows > 0 ? "Username already exists" : "Username doesn't exist" );
}
?>
<?php
/*
reg_process.php
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['cus_username'], $_POST['firstname'], $_POST['lastname'], $_POST['email'], $_POST['password'] ) ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql = 'insert into `users` (`cus_username`, `firstname`, `lastname`, `email`, `password`) values (?,?,?,?,?);';
$stmt = $db->prepare( $sql );
if( $stmt ){
$username=!empty($_POST['cus_username']) ? $_POST['cus_username'] : false;
$firstname=!empty($_POST['firstname']) ? $_POST['firstname'] : false;
$lastname=!empty($_POST['lastname']) ? $_POST['lastname'] : false;
$email=!empty($_POST['email']) ? $_POST['email'] : false;
$password=!empty($_POST['password']) ? $_POST['password'] : false;
$errors=array();
if( !$username )$errors[]='Please enter a username';
if( !$password )$errors[]='Please enter your password';
if( !$email )$errors[]='Please enter your email';
if( !$firstname )$errors[]='Your firstname is required';
if( !$lastname )$errors[]='Your lastname is required';
if( empty( $errors ) ){
/* bind the variables and execute the sql statement */
$stmt->bind_param('sssss', $username, $firstname, $lastname, $email, $password );
$result = $stmt->execute();
echo $result ? 'Success' : 'Failed';
} else {
foreach( $errors as $error ){
echo $error . '<br />';
}
}
$stmt->close();
$db->close();
}
}
?>
I created these three pages following the directory structure suggested by the javascript function and form target, changed the db details to suit dev environment and assumed a table called users - ran the page and completed the form. A new user was successfully added.

Error occur when login with switching database when company name is selected which related with $_SESSION

Im facing a problem Notice: Undefined index: company in C:\xampp\htdocs\new_exp\login.php on line 4
Errors
At here i have 3 database. exp, new_1 and new_2. In exp database have company table which contain id, company_name, and database_name attributes.
There are two database connection that i use which are dbconnection_main.php and dbconnection.php. dbconnection_main.php i used to call ada database which storing company_name and database_name table. Once user selected option of company_name when login in same time it will call the database_name.
The error occur when i login.
This is my index.php
<?php
session_start();
error_reporting(-1);
// Cek Active Link
function ActiveClass($requestUri)
{
$current_file_name = basename($_SERVER['REQUEST_URI'], ".php");
if ($current_file_name == $requestUri)
echo 'class="active"';
}
//check already login
if (!isset($_SESSION['UserId'])) {
header ('Location: login');
exit;
}
if ($_SESSION['level'] == 'APPROVAL'){
header ('Location: login');
exit;
}
//Link to page
if (isset($_GET['page']) && $_GET['page'] == 'ManageCategory') {
$page = "ManageExpenseCategory";
} else {
$page = 'dashboard';
}
//get global notification
include('includes/global.php');
//Get Header
include('includes/header.php');
//set global message notification
$msgBox ="";
if (file_exists('pages/'.$page.'.php')) {
// Load the Page
include('pages/'.$page.'.php');
} else {
// Else Display an Error
echo '
<div class="wrapper">
<h3>Err</h3>
<div class="alertMsg default">
<i class="icon-warning-sign"></i> The page "'.$page.'" could not be found.
</div>
</div>
';
}
include('includes/footer.php');
?>
So here is my login.php
<?php
session_start();
error_reporting(-1);
$_SESSION['db_company_name'] = $_POST['company'];
$msgBox = '';
//include notification page
include ('includes/notification.php');
//Include db Page
require_once ('includes/dbconnection.php');
//Include Function page
include ('includes/Functions.php');
//User Login
if(isset($_POST['login']))
{
$username = $mysqli->real_escape_string($_POST['email']);
$Password = encryptIt($_POST['password']);
if ($stmt = $mysqli->prepare("SELECT UserId, company_id, FirstName, LastName, Email, Password, level, admin_access, Currency from user WHERE Email = ? AND Password = ? "))
{
$stmt->bind_param("ss", $username, $Password);
$stmt->execute();
$stmt->bind_result($UserId_, $CompanyId_, $FirstName_, $LastName_, $Email_, $Password_, $Level_, $Admin_access_, $Currency_);
$stmt->store_result();
$stmt->fetch();
if ($num_of_rows = $stmt->num_rows >= 1)
{
session_start();
$_SESSION['UserId'] = $UserId_;
$_SESSION['FirstName'] = $FirstName_;
$_SESSION['LastName'] = $LastName_;
$_SESSION['level'] = $Level_;
$_SESSION['admin_access'] = $Admin_access_;
$_SESSION['Currency'] = $Currency_;
$_SESSION['company_id'] = $CompanyId_;
$compId = $_SESSION['company_id'];
$UserIds = $_SESSION['UserId'];
$company_q = mysqli_query($mysqli, "SELECT * FROM company_setting where company_id = '".$compId."'");
$company = mysqli_fetch_assoc($company_q);
$_SESSION['company_name'] = $company['company_name'];
if ($_SESSION['level'] === 'STAFF'){
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index">';
}
else
{
$msgBox = alertBox($LoginError);
}
}
}
}
?>
<!DOCTYPE html>
<html>
<div class="panel-body">
<?php if ($msgBox) {
echo $msgBox;
} ?>
<form class="form-horizontal m-t-20" method="post" action="" role="form">
<div class="form-group ">
<div class="col-xs-12">
<input class="form-control" onBlur="checkcompany(this.value)" type="email" required placeholder="<?php echo $Emails; ?>" name="email" id="email" autofocus>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input class="form-control" type="password" name="password" value="" required placeholder="<?php echo $Passwords; ?>">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<span id="result"><select name="company" id="company" class="form-control" required><option>company</option></select></span>
</div>
</div>
<div class="form-group text-center m-t-40">
<div class="col-xs-12">
<button type="submit" name="login" class="btn btn-primary btn-block text-uppercase waves-effect waves-light"><?php echo $SignIn; ?></button>
</div>
</div>
</form>
</div>
<script>
function checkcompany(v)
{
//alert(v);
var dataString = 'email='+v;
//document.getElementById('loginbtn').style.display = "none";
$.ajax({
type: "POST",
url: "checkaccount.php",
data: dataString,
cache: true,
success: function (result){
$("#result").html(result);
//document.getElementById('loginbtn').style.display = "block";
}
})
}
</script>
This is my checkaccount.php
<?php
error_reporting(-1);
session_start();
include("includes/dbconnection_main.php");
$email = $_POST['email'];
?>
<select name="company" id="company" class="form-control" required>
<option value="">----------------</option>
<?php
$company_q = mysqli_query($mysqli, "SELECT * FROM company");
while($company = mysqli_fetch_assoc($company_q))
{
//connect to sub database
$conn_hostname = "localhost";
$conn_database = $company['database_name'];
$conn_username = "root";
$conn_password = "";
$mysqlii = new mysqli($conn_hostname, $conn_username, $conn_password, $conn_database);
$check_q = mysqli_query($mysqlii, "SELECT * FROM user WHERE Email = '".$email."' AND status = 'ACTIVE' AND password != ''");
$check = mysqli_num_rows($check_q);
if (!$check) {
printf("Error: %s\n", mysqli_error($mysqlii));
exit();
}
if($check >= 1)
{
?>
<option value="<?php echo $company['company_name']; ?>"><?php echo strtoupper($company['company_name']); ?></option>
<?php
}
mysqli_close($mysqlii);
}
?>
</select>
SO this is my dbconnection_main.php
<?php
error_reporting(-1);
ini_set('display_errors', '0');
$dbuser="root";
$dbpassword="";
$dbname="exp";
$dbhost="localhost";
$mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
?>
And This is my dbconnection.php
<?php
error_reporting(-1);
ini_set('display_errors', '0');
if(!isset($_SESSION))
{
session_start();
}
$dbuser="root";
$dbpassword="";
$dbname="exp";
$dbhost="localhost";
if($_SESSION['db_company_name'] != '')
{
$company_name = $_SESSION['db_company_name'];
}else
{
$company_name = $_POST['company_name'];
$_SESSION['db_company_name'] = $company_name;
}
$mysqlie = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
$get_database_q = mysqli_query($mysqlie, "SELECT * FROM company WHERE company_name = '".$company_name."'") or trigger_error(mysqli_error($mysqlie),E_USER_ERROR);
$get_database = mysqli_fetch_assoc($get_database_q);
if (!$get_database) {
printf("Errors: %s\n", mysqli_error($mysqlie));
exit();
}
$conn_hostname = "localhost";
$conn_database = $get_database['database_name'];
$conn_username = "root";
$conn_password = "";
$mysqli = new mysqli($conn_hostname, $conn_username, $conn_password, $conn_database);
?>
I cannot detect the error since it only give me such general error prompt out. I think it might be related with dbconnection.php at this part which related with $_session..
if($_SESSION['db_company_name'] != '')
{
$company_name = $_SESSION['db_company_name'];
}else
{
$company_name = $_POST['company_name'];
$_SESSION['db_company_name'] = $company_name;
}

Ajax file upload not working in Chrome

I tested this script in Safari, and there it works, but I tried in Chrome, and there it does not work, and doesn't print the $status. What's the problem?
HTML file:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<span id="success"></span>
<form id="upload" method="post" enctype="multipart/form-data">
<input type="text" name="username" id="username">
<input type="file" name="imagefile" id="imagefile">
<input type="submit" name="uploadsubmit" id="uploadsubmit">
</form>
<script>
$(document).ready(function(){
$('#upload').on('submit', function(e) {
e.preventDefault();
var username = $('#username').val();
if (username == '') {
alert("Empty!");
} else {
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data) {
$('#success').html(data);
alert("Success!");
}
});
}
});
});
</script>
PHP file:
<?php
$connect = mysqli_connect("localhost", "root", "", "db");
$con=mysqli_connect("localhost","root","","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$status = '';
if(isset($_POST['uploadsubmit'])) {
$username = $_POST["username"];
if($_FILES['imagefile']['name'] != '') {
$target = "/images";
$target = $target . basename($_FILES['imagefile']['name']);
if (move_uploaded_file($_FILES['imagefile']['tmp_name'], $target)) {
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (username,images)
VALUES ('".$username."','".$target."')");
mysqli_close($con);
$status = "Successfull upload with image!";
$imagefile = pathinfo($target, PATHINFO_EXTENSION);
$check = getimagesize($target);
if ($check !== false) {
echo "This file is image - " . $check["mime"] . ".<br>";
$uploadOk = 1;
} else {
echo "This file is not image!";
$uploadOk = 0;
}
} else {
$status = "Sorry, we have problem!";
}
} else {
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (username,images)
VALUES ('".$username."','no')");
mysqli_close($con);
$status = 'Successfull upload without image!';
}
echo "Status: {$status}";
}
?>

Categories

Resources