java script alerts always appear - javascript

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.

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.

How can I show a DIV element without creating a new row?

I crated a small login form where I check the username in a external php file. After that I give back an error message or redirect to another site.
My problem is to show the error message. I want a short message above the login form if the username != „test“. In my script, the errormessage appears above the login form, but the login form jumps one row deeper.
Question 1:
How can a create a placeholder above the login form? So that the login form is fix?
Question 2:
Is it the right way to fill a JavaScrpt Variable in PHP as in my Code?
Thanks for your help!
< script >
var error_login;
if (error_login == 1) {
$('#errorText').show();
} else {
$('#errorText').hide();
} <
/script>
<?php
//debug
error_reporting(-1);
ini_set('display_errors', true);
session_start();
session_unset();
session_destroy();
?>
<!doctype html>
<html lang="de">
<head>
<title>Hello World</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</head>
<body>
<?php include ("login.php"); ?>
<div class="container">
<div id="errorText" class="row justify-content-center">
Login failed!
<!-- This should be a placeholder -->
</div>
<!-- Formular Beginn -->
<div class="row justify-content-center">
<div class="col-md-6">
<form class="form" role="form" method="post" action="?login=1" accept-charset="UTF-8" id="login">
<div class="input-group" id="frmGrpBenutzer">
<input type="password" class="form-control input-lg" id="user" name="user" placeholder="Username" required autofocus>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary btn-custom btn-lg" title="login" id="loginbtn"><span>Go</span></button>
</span>
</div>
</form>
</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<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.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
Here the login.php file:
<?php
session_start();
if(isset($_GET['login'])) {
$user = $_POST['user'];
if ($user == "test") {
$_SESSION['username'] = $user;
header('Location: site2.php');
} else {
echo "<script>
var error_login = 1;
</script>";
}
}
There are a few possibilities. The easiest would be to set your div with an opacity:0 or visibility:hidden this will make it still take space in the document flow.
Another option, could be to set it's position:absolute this will prevent it to take space inside your login form. Doing this will make it overlap tough, so there would need to be a padding or margin to offset the content of the form.
As for setting your javascript variable with PHP, that's one way to do it yes, but your script already defines error_login... Another way to do it, is use a holder HTML element, give it an id, and a data-* attribute. This will make it very easy to read the information from code:
$('button').click(function() {
console.log($('#login_status').data('login-error'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="login_status" data-login-error="1"></div>
<button>Click me to get result</button>
You could also add all the data you want into a JSON string as the div's content, and parse it once the page loaded.

Notice: Undefined index: password in E:\x\htdocs\crud\slp\slp\login.php on line 10 [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
Where I'm wrong? this error only orccur when I use data-toggle="password" - see the code below.
https://gist.githubusercontent.com/pomy/77047de0962f6a17d8459a8a51083952/raw/997f33425212eba407902dfa9e0e6ad52180e033/%2520data-toggle=%2522password%2522
<?php
session_start();
require_once "config.inc.php";
$email = '';
$password='';
$errors = array();
//Checking the request method post to know if the form really posts any data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
//perfroming the validation
if(empty($email)){
$errors[] = "Email field is required";
}
if(empty($password)){
$errors[] = "Password field is required";
}
//You are goo to go
if(empty($errors)) {
$sth = $conn->prepare("SELECT * FROM users WHERE email = :email LIMIT 1");
$sth->bindParam(':email', $email, PDO::PARAM_STR);
$sth->execute();
$user = $sth->fetch(PDO::FETCH_OBJ);
if(!empty($user)) {
//Verifying the password
$hashedPwdDB = $user->password;
if (password_verify($password, $hashedPwdDB)) {
$_SESSION['user_id'] = $user->user_id;
$_SESSION['name'] = $user->name;
$_SESSION['email'] = $user->email;
header("Location:dashboard.php");
exit;
}
else {
$errors[] = "Invalid login";
}
}
else {
$errors[] = "Invalid login";
}
}
}
?>
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Tutsplanet Login Form</title>
<!-- Bootstrap -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">
<!-- login with show password -->
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-show-password/1.0.3/bootstrap-show-password.min.js"></script>
</head>
<!-- login with show password // -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script></head>
<body>
<div class="container" style="width:20%;">
<form class="form-signin" method="post">
<?php if(!empty($errors)):?>
<div class="alert alert-danger">
<?php foreach($errors as $error):?>
<?php echo $error,"<br>";?>
<?php endforeach;?>
<?php endif;?>
</div>
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus name="email">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="password" name="password" class="form-control" data-toggle="password" autocomplete="off">
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div>
<!-- /container -->
<script type="text/javascript">
$("#password").password('toggle');
</script>
</body>
</html>
I solved it by adding if (isset ($_GET ["password"])) {} after line number 6. Error has gone. Is it a good approach to fix like this?

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