Javascript addEventListener doesn't execute - javascript

I have a form used to reset a password. On client side I am using vannila js to check if the input is valid however the javascript code doesn't execute completely. It gets the form,password and repeated password id's but it doesn't stop the form from submitting or executing the validation functions.
This is the password reset form. For server side I am using php to check if the proper values exist. If they don't the user can't access the page and the form doesn't exist. However all the data exists so I can see the form
<?php
require_once "../classes/dbh.classes.php";
require_once "../classes/reset-password.class.php";
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!--Bootstrap link -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!--Bootstrap icons link-->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.3.0/font/bootstrap-icons.css">
<!--Mapbox css link (optional)-->
<link href='https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css' rel='stylesheet'/>
<!--Custom styles link-->
<link rel="stylesheet" href="../CSS/style.css">
<!--JQUERY LINK-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>LP Budgeting - reset password</title>
</head>
<body>
<!--HEADER START-->
<!--navbar start-->
<nav class="navbar navbar-expand-lg bg-black navbar-dark py-3 fixed-top">
<div class="container">
LP<span class="text-warning">Budgeting</span>
<button class="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navmenu"
>
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navmenu">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
Home
</li>
</ul>
</div>
</div>
</nav>
<!--navbar end-->
<!--HEADER END-->
<!--RESET PASSWORD FORM START-->
<div class="py-5">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h5>Reset your password</h5>
<p>Please fill out the fields below and your password will be changed</p>
</div>
<div class="card-body">
<?php
if ($_GET['token'] && $_GET['email']) {
$token = $_GET['token'];
$email = $_GET['email'];
$check_user_class = new reset_password();
if ($check_user_class->check_user_4reset($email, $token)) {
?>
<form method="post" name="reset-form" id="reset-form" action="submit_new_password.php">
<?php
$fullUrl = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if (strpos($fullUrl, "error=passwords-mismatch") == true) {
if (isset($_SESSION["password-mismatch"])) {
echo $_SESSION["password-mismatch"];
unset($_SESSION["password-mismatch"]);
}
} elseif (strpos($fullUrl, "error=empty_fields") == true) {
if (isset($_SESSION['empty-passwords'])) {
echo $_SESSION["empty-passwords"];
unset($_SESSION["empty-passwords"]);
}
} else {
if (isset($_SESSION["password-change-success"])) {
echo $_SESSION["password-change-success"];
unset($_SESSION["password-change-success"]);
}
}
?>
<div class="form-group mb-3">
<input type="hidden" name="email" value="<?php echo $email; ?>">
<input type="hidden" name="token" value="<?php echo $token; ?>">
<label for="password">Enter New password</label>
<input type="password" id="password" class="form-control" name='password'
placeholder="New password"><br>
<label for="password2">Repeat your password</label>
<input type="password" id="password2" class="form-control"
name='password_repeat' placeholder="Repeat your password">
</div>
<div class="form-group mb-3">
<input type="submit" id="submit_password" name="submit_password"
class="btn btn-primary">
</div>
</form>
<!--Custom Javascript-->
<script src="../js/password-reset-error-handling.js" type="module"></script>
<!--RESET PASSWORD FORM END-->
<?php
} else {
//That user doesn't exist
echo "error";
}
}
?>
<!--Javascript/Bootstrap links-->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
</body>
</html>
The javascript code
const reset_form = document.getElementById('reset-form');
const password = document.getElementById('password');
const password_repeat = document.getElementById('password2');/////////////////all of these variables have the proper value i.e the id of the input fields and the form
reset_form.addEventListener('submit', e => { /////////this is the part that it skips
if (validateInputs()) {
e.currentTarget.submit();
} else {
e.preventDefault();
}
});
function validateInputs() {
//Get the value from inputs
const passwordValue = password.value.trim();
const passwordRepeatValue = password_repeat.value.trim();
let return_value = false;
//These variables are set with one when the value of the input field is correct
let password_check = 0;
let password_repeat_check = 0;
if (passwordValue === '') {
//Show error and set error class
setError(password, 'Password field cannot be empty');
} else if (passwordValue.length <= 6) {
setError(password, 'Please enter a longer password');
} else {
//Add success class
setSuccess(password);
password_check = 1;
}
if (passwordRepeatValue === '') {
//Show error and set error class
setError(password_repeat, 'Password repeat field cannot be empty');
} else if (passwordValue !== passwordRepeatValue) {
setError(password_repeat, 'The passwords do not match');
} else if (passwordRepeatValue.length <= 6) {
setError(password_repeat, "Repeated password needs to be longer")
} else {
//Add success class
setSuccess(password_repeat);
password_repeat_check = 1;
}
if (name_check === 1 && email_check === 1 && password_check === 1 && password_repeat_check === 1) {
return_value = true;
} else {
return_value = false;
}
return return_value;
}
function setError(element, message) {
element.className = "form-control error";
const small = document.getElementById("message-" + element.id);
small.classList.remove('success');
//Add error message and icon
small.innerHTML = message + ' <i class="fas fa-exclamation-circle">';
//Add error class
small.classList.add("error");
}
const setSuccess = (element) => {
element.className = "form-control success";
const small = document.getElementById("message-" + element.id);
small.classList.remove('error');
//Add success icon
small.innerHTML = '<i class="fas fa-check-circle">';
//Add success class
small.classList.add("success");
}

Related

HTML alert gets displayed before hitting the submit button [duplicate]

This question already has answers here:
Checking if form has been submitted - PHP
(9 answers)
Closed 7 months ago.
i have been trying to create a login page linked to a database . I have created an alert which is supposed to be displayed after invalid login or empty login but it gets displayed
right after the login page is loader(i.e. before any submission) .For example as soon as the page loads it displays an alert which says"Username password cannot be empty" .I want this alert to be shown after the user hits the submit button.Please Help.Here's the
image
Here's the code:
<?php
//error
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once "config.php";
session_start();
if (isset($_SESSION['username'])) {
header('location: home.php');
exit;
}
$username = "";
$password = $err = "";
if (isset($_POST)) {
if (empty(trim($_POST['username'])) || empty(trim($_POST['password']))) {
$err = "Username or Password cannot be blank";
} else {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
}
if (empty($err)) {
echo "in";
$sql = "SELECT id,username,password FROM users where username=?";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "s", $param_username);
$param_username = $username;
if (mysqli_stmt_execute($stmt)) {
mysqli_stmt_store_result($stmt);
//if username exists
if (mysqli_stmt_num_rows($stmt) == 1) {
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if (mysqli_stmt_fetch($stmt)) {
if (password_verify($password, $hashed_password)) {
//password correct
session_start();
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
$_SESSION['loggedin'] = true;
header("location: home.php");
}
}
} else {
$err = "Invalid Username or Password";
}
}
}
}
?>
Here's HTML:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spotify</title>
<link rel="stylesheet" href="style1.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Varela+Round&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</head>
<body class="bds">
<nav>
<ul>
<a>
<li class="brand"><img class="hello" src="./images/logo.png" alt="Spotify">Spotify</li>
<div class="buttons">
<button class="home">Home</button>
<button class="home">About</button>
</div>
<div class="logbutton">
<button class="loginbutt">Register</button>
</div>
</ul>
</nav>
<div class="container mt-4">
<h3>Login Here</h3>
<hr>
<form action="" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="text" name="username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Username">
<small id="emailHelp" class="form-text text-muted">We'll never share your details with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<br>
<?php
if (!empty(trim($err))) {
echo "<div id='warningus' class='alert alert-warning alert-dismissible fade show' role='alert'>
<strong>Holy guacamole!</strong> " . $err . "
<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
</div>";
$err="";
}
?>
<br>
<button type="submit" class="btn btn-primary">Log in</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
</body>
</html>
Create an input with type="hidden" and give it a name and value. Then check for that input to determine if the page is loaded after a submit.

access table from PHP database in Javascript

I have created a login page that allows you to log in using username and password. However, it is currently so that you are always redirected to the "profile" page and there is then checked by PHP whether the login data are correct, because the data are on the DB.
Therefore I have the idea with a validate function directly on the loginpage to check if the data is correct and then I just create a session.
Does anyone have an idea how I can do this?
Here is the code:
<?php session_start();?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Login</title>
<link href="bootstrap_style.css" rel="stylesheet" id="bootstrap-css"> <!-- maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <!-- //maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js or bootstrap.js-->
<script src="jquery.js"></script> <!-- //cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrapper fadeInDown">
<div id="formContent">
<!-- Tabs Titles -->
<!-- Icon -->
<div class="fadeIn first">
<img src="default_logo2.png" id="icon" alt="User Icon" onclick="window.open('url', '_blank');"/>
</div>
<!-- Login Form -->
<form action="searchpage.php" method="post" onsubmit="validateForm(event);">
<input type="text" id="login" class="fadeIn second" name="username" placeholder="username">
<input type="password" id="password" class="fadeIn third" name="password" placeholder="password">
<input type="submit" class="fadeIn fourth" value="Log In">
</form>
<!-- Remind Passowrd -->
<div id="formFooter">
<a class="underlineHover" style="color:red" id="warning"></a>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
function validateForm(event) {
var input_username = document.getElementById("login");
var input_password = document.getElementById("password");
if (input_username.value == '' || input_username.value.charAt(0) == ' ' || input_password.value == '') {
event.preventDefault();
document.getElementById("warning").innerHTML = "Fill empty fields!";
}
else {
return true;
}
}
</script>
with this I reach the DB:
$pdo = new PDO('mysql:host=localhost;dbname=ausleihe', 'root', '');
and that is the SELECT:
$login_session = "SELECT * FROM login WHERE username = '".$hereshouldbetheusernamefromform."' AND password = '".herethepasswordfromform."'";
If you need more code or have questions, ask me!
Thx
Client-side JavaScript cannot directly access a Host-side PHP program except through AJAX calls. Only the Host-side software has access to Host-side databases.

What are the methods to limit the number and time of alerts?

when I click on the "Todo Ekleyin" button, I get a warning. However, I would like this alert to appear only once per press, not multiple times, and can be pressed again after the alert disappears. How can I achieve this and?
Thank you in advance for your answer, good work. (If there is a method other than the method you suggested, I would be glad if you can write its name.)
// Tüm Elementleri Seçme
const form = document.querySelector("#todo-form");
const todoInput = document.querySelector("#todo");
const todoList = document.querySelector(".list-group");
const firstCardBody = document.querySelectorAll(".card-body")[0];
const secondCardBody = document.querySelectorAll(".card-body")[1];
const filter = document.querySelector("#filter");
const clearButton = document.querySelector("#clear-todos");
eventListeners();
function eventListeners() { // Tüm Event Listenerlar
form.addEventListener("submit", addTodo);
}
function addTodo(e) {
const newTodo = todoInput.value.trim();
if (newTodo === "") { // Alarm Verme
showAlert("danger","Lütfen Bir Todo Giriniz");
}
else {
addTodoToUI(newTodo);
}
addTodoToUI(newTodo);
e.preventDefault();
}
function showAlert(type,message){
const alert = document.createElement("div");
alert.className = `alert alert-${type}`;
alert.textContent = message;
firstCardBody.appendChild(alert);
//setTimeout
setTimeout(function(){
alert.remove();
}, 1000);
}
function addTodoToUI(newTodo) { // String Değerini List Item olarak Ekleyecek.
// List Item Oluşturma.
const listItem = document.createElement("li");
// Link Oluşturma
const link = document.createElement("a");
link.href = "#";
link.className = "delete-item";
link.innerHTML = "<i class = 'fa fa-remove'></i>";
listItem.className = "list-group-item d-flex justify-content-between";
// Text Node
listItem.appendChild(document.createTextNode(newTodo));
listItem.appendChild(link);
// Todo List'e List Item'ı Ekleme
todoList.appendChild(listItem);
// Ekleme Sonrası Input'tan yazı Silme
todoInput.value = "";
}
// Todo Ekleme Bilgi Mesajı
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" />
<title>Todo List</title>
</head>
<body>
<div class="container" style="margin-top: 20px">
<div class="card row">
<div class="card-header">Todo List</div>
<div class="card-body">
<form id="todo-form" name="form">
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" type="text" name="todo" id="todo"
placeholder="Bir Todo Girin" />
</div>
</div>
<button type="submit" class="btn btn-danger">Todo Ekleyin</button>
</form>
<hr />
<!-- <div class="alert alert-danger" role="alert">
This is a danger alert—check it out!
</div> -->
</div>
<div class="card-body">
<hr />
<h5 class="card-title" id="tasks-title">Todolar</h5>
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" type="text" name="filter" id="filter"
placeholder="Bir Todo Arayın" />
</div>
</div>
<hr />
<ul class="list-group">
<!-- <li class="list-group-item d-flex justify-content-between">
Todo 1
<a href = "#" class ="delete-item">
<i class = "fa fa-remove"></i>
</a>
</li>-->
</ul>
<hr />
<a id="clear-todos" class="btn btn-dark" href="#">Tüm Taskları Temizleyin</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
</script>
<script src="berkay.js"></script>
</body>
</html>
You can put an integer in your alert function and every using array increase a one more.
For example, if you want after 5 times don't show alert.
var a = 0;
var b = true;
if (newTodo === "" || b) { // Alarm Verme
showAlert("danger","Please Give me a Todo!");
a++;
if(a == 5 ){
b = false;
}
}

java script alerts always appear

above the form
<?php require_once "core-admin/init-admin.php";
if( !isset($_SESSION['admin_username']) ){
$_SESSION['msg'] = 'page can not open';
header('Location:admin_login.php');
}
if(isset($_POST['submit']) ){
$press_type = $_POST['press_type'];
$press_picture = $_FILES['press_picture'];
$type_file = $_FILES['press_picture'] ['type'];
$tmp_file = $_FILES['press_picture']['tmp_name'];
$file_size = $_FILES['press_picture'] ['size'];
if(!empty(trim($press_type)) ) {
if(!empty($_FILES['press_picture']['tmp_name']) ){
if($type_file == "image/jpeg" || $type_file == "image/png" || $type_file == "image/jpg" ){
if($file_size <= 300000){
if(add_press($press_type, $press_picture)) {
$message = 'sukses men.';
echo "<SCRIPT type='text/javascript'>
alert('$message');
window.location.replace(\"add_data_press.php\");
</SCRIPT>";
}
} else { ?>
<script>
alert("failed add data");
</script>
<?php }
}else{ ?>
<script>
alert("size should be below 200kb");
</script>
<?php }
}else{ ?>
<script>
alert("image type should be .jpeg .jpg atau .png");
</script>
<?php }
}else{ ?>
<script>
alert("image can not be empty");
</script>
<?php }
}else{ ?>
<script>
alert("please complete the unfilled form");
</script>
<?php
}
?>
form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title></title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="../view/css/bootstrap.min.css">
<link rel="stylesheet" href="../view/css/dataTables.bootstrap.min.css">
<!-- Custom styles for this template -->
<link href="../view/css/simple-sidebar.css" rel="stylesheet">
<link rel="stylesheet" href="../view/font-awesome/css/font-awesome.min.css">
</head>
<body>
<?php require_once"../view/header-admin.php";?>
<!-- /#sidebar-wrapper -->
<!-- Page Content if tdk ada ini tidak akan tampil apa apa -->
<div id="page-content-wrapper">
<div class="container-fluid">
<i class="fa fa-th text-danger" aria-hidden="" id="menu-toggle"></i>
<div class="row">
<div class="col-md-12">
<h1 class="display-4">Carolyn Tyler</h1>
<h6>handmade fine jewelry</h6>
<br>
<h5>Add data press</h5>
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-lg-8">
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="form-control-label" for="formGroupExampleInput">Press Type</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="Press Type" name="press_type" required="">
</div>
<div class="form-group">
<label for="exampleFormControlFile1">press picture</label>
<input type="file" class="form-control-file" id="exampleFormControlFile1" name="press_picture">
</div>
<button type="submit" class="btn btn-primary" name="submit">Submit</button>
<br> <br>
</form>
</div>
</div>
</div>
</div>
my problem is, when i access this page. I always get the alert "please complete the unfilled form". in this case I have not done any insert yet but have alerted this page.
but if I split the file # abovethepage # alerts do not show up again. is there any way to make # abovethepage # files still on 1 page but alert does not appear again.?
if you check isset($_POST['submit']) is return false on first time page load
if(isset($_POST['submit']))
thats why your else part run first time page load without submitting form data
When you access the page for the first time, the $_POST is empty(It will only contain data if you send HTTP POST request to your script using submit button). In such case, the below else condition satisfies:
else{ ?>
<script>
alert("please complete the unfilled form");
</script>
<?php
}
This is why it always shows the alert message.

How to show message that user is already registered in html through php?

I have an HTML form in which a user enter his/her email id to register everything is working great it checks the valid email id and also registered the email id ! But when I applied new code to check that the user is already registered or not it didn't work !!
Below is my Html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sign Up - MOBTRICKS</title>
<!-- CSS -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Lobster">
<link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Lato:400,700'>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="assets/css/style.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Favicon and touch icons -->
<link rel="shortcut icon" href="assets/ico/fa.png">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<!-- <script type="text/javascript">
function greeting(){
alert("Welcome ! Your Email : " + document.forms["form"]["email"].value + " has been registered under our records successfully !")
}
</script> -->
</head>
<body>
<!-- Header -->
<div class="container">
<div class="row header">
<div class="col-sm-4 logo">
<h1><a href=#>PQR</a> <span>.</span></h1>
</div>
<div class="col-sm-8 call-us">
<p>Mob: <span>+91-9530803237</span> | email: <span>ab.creations27#gmail.com</span>
</p>
</div>
</div>
</div>
<!-- Coming Soon -->
<div class="coming-soon">
<div class="inner-bg">
<div class="container">
<div class="row">
<div class="col-sm-12">
<center>
<i class="fa fa-cog fa-spin fa-3x fa-fw"></i>
<span class="sr-only">Loading...</span>
<h2>We're Coming Soon</h2>
<p>We are working very hard on the new version of our site. It will bring a lot of new features. Stay tuned!</p>
<div class="timer">
<div class="days-wrapper">
<span class="days"></span>
<br>days
</div>
<div class="hours-wrapper">
<span class="hours"></span>
<br>hours
</div>
<div class="minutes-wrapper">
<span class="minutes"></span>
<br>minutes
</div>
<div class="seconds-wrapper">
<span class="seconds"></span>
<br>seconds
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Content -->
<div class="container">
<div class="row">
<div class="col-sm-12 subscribe">
<h3>Subscribe to our newsletter !!</h3>
<p>Sign up now to our newsletter and you'll be one of the first to know when the site is ready:</p>
<form class="form-inline" role="form" action="assets/subscribe.php" method="post">
<div class="form-group">
<label class="sr-only" for="subscribe-email">Email address</label>
<input type="text" name="email" placeholder="Enter your email..." class="subscribe-email form-control" id="subscribe-email">
</div>
<button type="submit" class="btn">Subscribe</button>
</form>
***
<div class="success-message"></div>
<div class="error-message"></div>***
</div>
</div>
<div class="row">
<div class="col-sm-12 social">
<i class="fa fa-facebook"></i>
<i class="fa fa-twitter"></i>
<a href="https://github.com/ashu271994" data-toggle="tooltip" data-placement="top" title="GitHub">
<i class="fa fa-github"></i>
</a>
<i class="fa fa-google-plus"></i>
<i class="fa fa-pinterest"></i>
<i class="fa fa-envelope-o"></i>
</div>
</div>
</div>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© ASHISH BHARWAL
</li>
<li>Credits: AB-Creations
</li>
</ul>
</footer>
<!-- Javascript -->
<script src="assets/js/jquery-1.11.1.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
ipt src="assets/js/jquery.backstretch.min.js"></script>
<script src="assets/js/jquery.countdown.min.js"></script>
<script src="assets/js/scripts.js"></script>
<!--[if lt IE 10]>
<script src="assets/js/placeholder.js"></script>
<![endif]-->
</body>
</html>
Below is my Subscriber.php page
<?php
// Email address verification
function isEmail($email)
{
return (preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]| [[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email));
}
if ($_POST) {
// Enter the email where you want to receive the notification when someone subscribes
$emailTo = 'ab.creations27#gmail.com';
$subscriber_email = addslashes(trim($_POST['email']));
if (!isEmail($subscriber_email)) {
$array = array();
$array['valid'] = 0;
$array['message'] = 'Insert a valid email address!';
echo json_encode($array);
// $msg="wrong answer";
// echo "<script type='text/javascript'>alert('$msg');</script>";
} else {
$host = "somehostname";
$user = "username";
$pwd = "password";
$db = "demo1";
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sql_insert = "SELECT * FROM demotable WHERE subs='$subscriber_email'";
$stmt1 = $conn->prepare($sql_insert);
$stmt1->execute();
$result = $stmt1->fetchColumn();
if ($result == 0) {
$sql_insert = "INSERT INTO demotable (subs)
VALUES ('$subscriber_email')";
$stmt = $conn->prepare($sql_insert);
$stmt->execute();
$array = array();
$array['valid'] = 1;
$array['message'] = "Your Email : $subscriber_email has been registered with us ! Thanks for your subscription!";
echo json_encode($array);
} else {
$array = array();
$array['valid'] = 2;
$array['message'] = "You are already registered !!";
echo json_encode($array);
}
}
catch (Exception $e) {
die(var_dump($e));
}
}
}
?>
Now what is happening when I tried to add an invalid email id then it shows Invalid Email id in marked in HTML page but when I added a new user then add the data in my table and show message but in case of the user who is already registered it didn't show any message !! I also tried to make new functions having "echo json_encode($array)"; But this also won't work !! Tell me what am I missing or what's my mistake !! I am trying to sort it from the last 3 days !!
my scripts.js code below
$('.subscribe form').submit(function(e) {
e.preventDefault();
var postdata = $('.subscribe form').serialize();
$.ajax({
type: 'POST',
url: 'assets/subscribe.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 0) {
$('.success-message').hide();
$('.error-message').hide();
$('.error-message').html(json.message);
$('.error-message').fadeIn();
}
else if (json.valid == 1){
$('.error-message').hide();
$('.success-message').hide();
$('.subscribe form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
else {
$('.error-message').hide().empty();
$('.success-message').hide().empty();
$('.subscribe form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
}
});
});
Try changing
$result = $stmt1->fetchColumn();
to
$result = $stmt1->num_rows;
see if that works.
Finally got it working. The error was simple but yet difficult to find. lolz
$sql_insert = "SELECT * FROM demotable WHERE subs='$subscriber_email'";
should be like
** $sql_insert = "SELECT COUNT(*) FROM demotable WHERE subs='$subscriber_email'";**
Thank you all for your views. :)

Categories

Resources