Changing innerHTML in php errors - javascript

I am beginner in PHP.
My CODE
<?php
session_start();
$username = "ADMIN";
$host = "localhost";
$password = "chmuhammadsohaib123";
$database = "USER";
$con = mysqli_connect($host, $username, $password, $database);
$USERNAME = $_POST["lusername"];
$PASSWORD = $_POST["lpassword"];
if (isset($_POST["login"])) {
if (isset($_POST["loggedin"])) {
setcookie("RAUSERNAME", $USERNAME);
setcookie("RAPASSWORD", $PASSWORD);
}
$_SESSION["SRAUSERNAME"] = $USERNAME;
$_SESSION["SRAPASSWORD"] = $PASSWORD;
}
if (isset($_POST["login"])) {
$data = mysqli_query($con, "SELECT * FROM `INFO` WHERE `USERNAME` = '$USERNAME'");
if (mysqli_num_rows($data)>0) {
echo "<script type='text/javascript'>window.location.replace('../');</script>";
}
else {
print("<script type='text/javascript'>document.getElementsByClassName('errors').innerHTML = '<h1 class='redback'>SORRY, BUT THIS ACCOUNT DOESN'T EXISTS</h1>';</script>");
}
}
?>
MY HTML PAGE
<body>
<div class="errors"></div>
<fieldset class="replacement">
<legend>LOGIN</legend>
<h1>LOGIN WITH YOUR INFORMATION</h1><br><br>
<form method="POST" action="<?php $_SERVER["php_self"]; ?>">
<input type="text" name="lusername" placeholder="YOUR USERNAME">
<input type="password" name="lpassword" placeholder="YOUR PASSWORD" class="password">
<br>
<br>
<label>KEEP ME LOGGED IN: </label>
<input type="checkbox" name="loggedin" checked>
<br><br>
<input type="submit" name="login" value="LOGIN"></form>
</fieldset>
</div>
</body>
</html>
When I am changing innerHTML of errors as described above, it doesn't changes. It says ; is missing in console or sometimes that errors is null. How can I fix it?

At the point you echo your javascript code, the html element with the id errors dont exists inside the dom. So the return of getElementById will always be undefined.
<script>document.getElementById("errors")...</script>
... some more html
<div id="errors"></div>
You could fix this by calling the javascript code after the dom document is ready. Using jQuery, you could do this this way
// event handler for document ready
$(function() {
// at this point, the dom is ready and the 'errors' id exists
$('#errors').html("some error message");
});
This would work, but seems a little bit unnecessary. The better way would be to just echo the actual error message with php and don't use javascript to do this.
$error = false;
if (mysqli_num_rows($data)>0) {
header('location: ../');
} else {
$error = '<h1 class="redback">SORRY, BUT THIS ACCOUNT DOESN\'T EXISTS</h1>';
}
and later
<div class="errors">
<?php if ($error) echo $error; ?>
</div>

Related

Insert data from PHP to HTML

I have this PHP which picks up information from a form in HTML and I wanted to put that information on a div on other HTML
Nome: <?php
global $user;
$user = $_POST['user'];
echo ucfirst($user) ?>
<br />
Password: <?php
global $pass;
$pass = $_POST['pass'];
echo $pass ?>
<br />
Data de nascimento: <?php
global $date;
$date = $_POST['date'];
echo $date ?>
I have this HTML
// HTML that I get the information from
<form method="post" id="formDetails">
<label for="name">Nome: </label> <br>
<input type="text" id="username" name="user" placeholder="username"> <br> <br>
<label for="password">Password: </label> <br>
<input type="password" id="password" name="pass" placeholder="password"> <br> <br>
<label for="date">Nascimento: </label> <br>
<input type="text" name="date" id="datepicker" placeholder="Data de Nascimento"> <br> <br>
<button type="submit" id="btn">Submit </button>
</form>
// HTML that I want to insert the data
<h1> Dados Pessoais </h1>
<div>
<div class="mensagem" id="mensagem"></div>
</div>
And I'm using this js line
// AJAX PART
var uName = $("input[name=user]").val();
var passwrd = $("input[name=pass]").val();
var dat = $("input[name=date]").val();
$("#formDetails").submit(function(){
$.post('process.php', {user: uName, pass: passwrd, date: dat})
.done(function(data) {
window.location.href = 'informacoes.html';
$('.mensagem').html(data);
$('.mensagem').show();
});
});
I had this code before and it didn't work either
// AJAX PART
var uName = $("input[name=user]").val();
var passwrd = $("input[name=pass]").val();
var dat = $("input[name=date").val();
$("#formDetails").submit(function(){
$.ajax({
type: 'POST',
url: 'process.php',
data: $("form").serialize(),
success : function(data) {
if($("#mensagem").hasClass('mensagem')){
$(".mensagem").html(data);
$(".mensagem").show();
} else {
$(".back").html(data);
$(".back").show();
}
},
error: function (xhr,ajaxOptions,throwError){
alert("erro");
},
});
return false;
I tried to get the information from data and put it inside the div class "mensagem" and show her but when it submits goes to the other HTML neither shows me the div neither the information and when I inspected element on browser I put the div visible and the information wasn't there and I don't really know what to do and I searched and I couldn't find anything useful
You are just making it to complicated for a simple form.I would suggest you to make a connection.php file where in you connect you database to Your table
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
create an index.php file.
Create a regular html submit form.
Include this button to your form.
<button type="submit" id="btn" name="submit-btn">Submit </button>
Add this piece of php code above and this creates a function to your button
<?php
require $connection;
if(isset($_POST['submit-btn'])){
$user = $_POST['user'];
$pass = $_POST['pass'];
$date = $_POST['date'];
try{
$insert_query = "INSERT INTO `table_name`(`column_1`, `column_2`, `column_3`) VALUES (:column_1, :column_2, :column_3)";
$query_exec = $con->prepare($insert_query);
$query_exec ->execute(array(":column_1" => $user, ":column_2" => $pass, ":column_3" => $date));
}
catch(PDOException $e) {
echo "Error: Data Insertion Failed";
}
}
?>

My registration form was working perfectly on localhost but now that it is on a c-panel server it doesn't work

This is my code, I really don't know whats wrong does anyone else know? Currently the error that comes up is Oops! Something went wrong. Please try again later. I know that the issue is not a connection issue and is not a permissions issue. I'm really confused about what I've done wrong and have even contacted customer support multiple times and they didn't know what the issue is.
<?php
include ('config.php');
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT username FROM users WHERE username = ?";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Validate password
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location:Login.php");
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? Login here.</p>
</form>
</div>
</body>
</html>

"Email is required" error in PHP registration script

I'm currently writing a script that preforms basic user registration.
When the user arrives on the landing page, I have a JS script that identifies their email from the URL and fills it in the email input box (which is disabled). After, the user just needs to put in their password to create an account. However, PHP throws the error "Email is required" even though it's been filled by the JS script.
I've tried to change the status of the input box to disabled to enabled which doesn't do much to help. I've attached the files involved in the process below. Any help would be greatly appreciated.
fillEmail.js
$(document).ready(function() {
var link = window.location.href;
var emailIndex = link.indexOf("email");
if(emailIndex != -1) {
link = link.substring(emailIndex + 6);
} else {
link = "";
}
document.getElementById("email").value = link;
//$('#email').attr('disabled', 'disabled');});
register.php
<?php include('server.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="header">
<h2>Register</h2>
</div>
<form method="post" action="register.php">
<?php include('errors.php'); ?>
<div hidden class="input-group">
<label>Username</label>
<input type="text" name="username" value="user">
</div>
<div class="input-group">
<label>Email</label>
<input type="email" name="email" id="email" value="<?php echo $email; ?>" disabled>
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm password</label>
<input type="password" name="password_2">
</div>
<div class="input-group">
<button type="submit" class="btn" name="reg_user">Register</button>
</div>
</form>
</body>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous">
</script>
<script type='text/javascript' src="fillEmail.js"></script>
</html>
server.php
<?php
session_start();
// initializing variables
$username = "";
$email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'registration');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO users (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
?>
I'm fairly new to PHP so any help would be greatly appreciated. Thanks so much in advance!
As per my comment, you can simply use readonly instead of disabled to achieve a similar effect. Also please use prepared statements to protect against SQL injection. mysqli_real_escape_string is not enough
In order for the value to be submitted the field cannot be disabled.
Simple solution, create another fields as (hidden), these are submitted
<input type="email" id="email" value="<?php echo $email; ?>" disabled>
<input type="hidden" name="email" value="<?php echo $email; ?>">
Or you could simply change the attribute from disables to readonly

How to save data in my database with PHP

When I send data to my php file. Data is not getting stored in the database. My php code is below.
I am using one.com as my host. There I can use to php code using some components. So I gave an external link to the button to submit to php file.
But I cannot submit data to php code using button name or class attribute.
How can I store data in database using php file.
Please help me in this issue.Thank you in advance.
HTML:
<form method="post" action="register.php">
<div class="input-group">
<lable>Username</lable>
<input type="text" name="Username" required>
</div>
<div class="input-group">
<lable>Email</lable>
<input type="text" name="Email" required>
</div>
<div class="input-group">
<lable>Password</lable>
<input type="password" name="password_1" required></div>
<div class="input-group">
<lable>Confirm Password</lable>
<input type="password" name="password_2" required>
</div>
<p>Already a User?</p>
</form>
PHP:
<?php
$Username = "";
$Email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('hostname', 'root', 'password', 'dbname');
echo "database connected";
// if the register button is clicked
$username = $_POST['Username'];
$email = $_POST['Email'];
$password_1 = $_POST['password_1'];
$password_2 = $_POST['password_2'];
echo "data is taken";
// if there are no errors, save user to database
$sql = "INSERT INTO Users(Username, Email, password) VALUES('$username',
'$email', '$password_1')";
mysqli_query($db, $sql);
echo "data inserted successfully";
?>
Is your database correct?
// connect to the database
$db = mysqli_connect('hostname', 'root', 'password', 'dbname');
echo "database connected";
And remember it always printed "database connected".

Login form using PHP and JQuery to validate login information from MySQL database

I have a login form that uses JQuery and PHP to validate a username and password. I am trying to switch over from extension mysql to mysqli for better practice and am having a lot of trouble. I think the error exists in the JQuery somewhere because I've tested the login.php validation and it works fine.
So here is my code:
index.php:
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#login_a").click(function(){
$("#shadow").fadeIn("normal");
$("#login_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function(){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function(){
var username=$('#user_name').val();
var password=$('#password').val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true'){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
}
else{
$("#add_err").html("*Wrong username or password");
}
},
beforeSend:function(){
$("#add_err").html("Loading...")
}
});
return false;
});
});
</script>
</head>
<body>
<?php session_start(); ?>
<div id="profile">
<?php if(isset($_SESSION['user_name'])){ ?>
<a href='logout_script_2.php' id='logout'>Logout</a>
<?php }else {?>
<a id="login_a" href="#">login</a>
<?php } ?>
</div>
<div id="login_form">
<form action="login_script_2.php" method="POST">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name" />
<label>Password:</label>
<input type="password" id="password" name="password" />
<label></label><br/>
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
<div class="err" id="add_err"><br></div>
</div>
<div id="shadow" class="popup"></div>
</body>
</html>
login.php
<?php
session_start();
$con = mysqli_connect("localhost","root","PW","db") or die("Connection error: " . mysqli_error($con));
if(isset($_POST['submit'])){
$username = $_POST['name'];
$password = $_POST['pwd'];
$stmt = $con->prepare("SELECT * FROM tapp_login WHERE username = ? AND password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1)
{
if($stmt->fetch())
{
$_SESSION['Logged'] = 1;
$_SESSION['user_name'] = $username;
echo 'Access granted';
exit();
}
}
else {
echo "*Wrong username or password";
}
$stmt->close();
}
else {
}
$con->close();
?>
logout.php
<?php
session_start();
unset($_SESSION['user_name']);
header('Location: index.php');
?>
All the attempts to run the code give me the error in the JQuery validation "*Wrong username or password". Thanks in advanced!
When logging in using ajax, you are not posting submit, so this line
if(isset($_POST['submit'])){
is never true so your code never executes.
Either change it to
if(isset($_POST['name'])){
or add it to your ajax posted data
data: "submit=true&name="+username+"&pwd="+password,
AJAX is a partial submission. Make sure you're firing it without using a submit button, or return false; inside your click function, at the bottom. I would use <input type='button' id='login_a' />, if it's not a link. Additionally, you are not setting your submit button, like #Sean said, because it's AJAX.

Categories