Simple Javascript Validation - Not Working - javascript

I've been stuck on this for longer than I intended for such a simple thing, any ideas why the intended validation is not working?
if(isset($_POST['submit'])){
/* Posted Values from Initial Form */
$descEmail = $_POST['email'];
$uniqueID = $_POST['name'];
/* Check to see if the Email Provided is already in use */
$result = mysql_query("SELECT * FROM Table WHERE Email = '$descEmail'");
if(mysql_num_rows($result) == 0) {
echo 'success';
} else {
echo '<script type="text/javascript"> emailInvalid() </script>';
}
}
The Javascript:
<script type="text/javascript">
function emailInvalid(){
document.getElementById('UserEmail').style.borderColor='#CC0033';
document.getElementById('UserEmail').style.border='solid';
document.getElementById('UserEmail').style.borderWidth='2px';
document.getElementById("formErrors").innerHTML = "The Email Address: <?php echo $UserEmail ?> has already been used, Please Use a Different Email Address.";
}
</script>
The form field in question: (Form is working as expected)
<div>
<label for="email">Email</label>
<input type="email" id="UserEmail" name="email">
</div>

Uncaught ReferenceError: emailInvalid
You appear to have defined your emailInvalid in a <script> element that appears after the one in which you try to call the function (on possibly one on a different page).
You can't call a function before it exists. Change the order of your code so the function is declared before you try to call it.

Related

How to prevent form refresh but submit form data on same page?

My form kept submitting and then refreshing so I looked at How to prevent page from reloading after form submit - JQuery to figure out how to stop it. The difference in the answer, however, with my solution was that I was submitting the form to itself.
Here's my code:
HTML
<form autocomplete="off" method="post" name="rp">
<input placeholder="Code" type="text" name="code" required>
<button type="submit">Submit</button>
</form>
PHP
<?php
$response = "";
if(isset($_POST['code'])){
echo "<script> alert('test'); </script>";
$password = $_POST["code"];
$result = $connection->query("SELECT * FROM Users WHERE passwords = '$password' LIMIT 1");
if($result->num_rows != 0) {
// unpack object
$data = mysqli_fetch_array($result);
// retrieves user ID (set into a cookie for x amount of time?)
$id = $data["ID"];
mysqli_close($connection);
echo "<script> alert('test 2'); </script>";
$response = "test 2";
header("Location: assessment.php");
} else {
$response = "test 3";
echo "<script> alert('test 3'); </script>";
mysqli_close($connection);
}
}
?>
JS
$("form").submit(function (e) {
// prevent page refresh
e.preventDefault();
var formData = $(this).serialize();
// Make AJAX request
$.post("login.php", formData);
});
I want the form to submit the data but not refresh. What am I doing wrong?
EDIT:
The problem has been narrowed down to the php. Since the request is through javascript, what should the name in the if-statement argument be. It can't be 'rp'.
So I found out something extremely curious. When I changed the if statement to if(isset($_POST['code']){} as some urged me to in the comments and I entered in the correct password, it follows the correct loop and produces this error:
VM1368 jquery.min.js:2 GET http://localhost:8080/assessment 404 (Not Found)
However, it does not produce the alert code I place before the header(). When I put in an incorrect password, it also doesn't do anything (even though I have an else statement). I've updated the php section to include most of the code. The $response variable and the echo/alerts are for debugging.
Final Edit:
Ironically, the reason none of my debugging wasn't working was because the page wasn't refreshing so alerts and variable updates wouldn't happen. (My quest to stop page refresh created all these problems). The solution to my original question was provided by MH2K9 and Toni Michel Caubet in the comment section. Thank you to them and others who tried to help.
Try this :
HTML :
<form autocomplete="off" method="post" name="rp" onsubmit="return false;">
<input placeholder="Code" type="text" name="code" required>
<br>
<button type="submit">Submit</button>
<button id="back_button" type="button"><img src="pics/back_arrow.png">Back</button>
</form>
JS:
$("form").submit(function (e) {
// prevent page refresh
e.preventDefault();
var formData = $(this).serialize();
// Make AJAX request
$.post("login.php", formData , function(data) {
alert(data);
$("form").reset();
});
});
You can alternatively call a function using the onsubmit attribute in HTML.
<form onsubmit='return preventSubmit(e)'>
// form content
</form>
<script>
function preventSubmit(e) {
e.preventDefault()
return false
}
</script>

Creating a simple Password login without the password hardcoded [PHP,Javascript,MySQL]

I'm trying to create a simple login promt on my local website. I already tried with Javascript, but I don't want the password to be hardcoded. The Users get the password by mail so there is no registration form needed. I searched on the Internet and I think it should work with PHP and Javascript. This is what i've come up with:
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Enter password',' ');
while (testV < 3) {
if (!pass1)
window.open('Website.html',"_self");
if (pass1.toLowerCase() == "password") {
alert('Correct!');
window.open('./test/sitetwo.html',"_self");
break;
}
testV+=1;
var pass1 =
prompt('Wrong Password','Try again');
}
if (pass1.toLowerCase()!="password" & testV ==3)
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Protected Area" onClick="passWord()">
</FORM>
</CENTER>
Does anyone of you know how to code this? Thank you for your help.
Login prompt is just one of possible approaches to hide information on your website. You have to decide first what are you trying to hide. For instance, if you if are providing some paid information to your clients - you can send the information itself by mail (instead of password). If you want to hide some part of site from other people - you can just give it weird url, like site.com/jkhgdsdkgf
Creating login backend with php and database obviously requires your php, mysql (or other database) and server administration skills and completely depends on details of your task, so it's hard to provide a useful advice here.
In my opinion, you should use a database to store all your credentials (like username, password, etc..)
If you don't know how to do it, you should know that if you want to run your php code, you need a php server and somewhere to put your db.
Here is how to set up a php server with Apache
https://www.ultraedit.com/support/tutorials-power-tips/uestudio/local-php-mysql-dev-environment.html
Here is how to set up a db with PhpMyAdmin
https://www.siteground.com/tutorials/phpmyadmin/create-populate-tables/
You need a login.php (where you log in), a test.php page (then you put in it whatever you want) and a check_User.php page (where to control if the credentials are correct).
Login.php
<html>
<head> <title>Login</title> </head>
<body>
<form action="check_User.php" method="post" id="login_form">
<label><b>Username</b></label>
<!-- USERNAME -->
<input type="text" placeholder="Enter Username" name="username" required>
<!-- PASSWORD -->
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<!-- LOGIN -->
<button type="submit">Login</button>
</form>
<body>
</html>
check_User.php
<?php
session_start();
$_POST["username"] = htmlspecialchars($_POST["username"]);
$_POST["password"] = htmlspecialchars($_POST["password"]);
$link = mysqli_connect("your_host", "your_db_username", "your_db_password", "your_db_name");
$query = "SELECT username, password
FROM your_db_name
WHERE username = \"".$_POST["username"]."\" AND password = \"".$_POST["password"]."\"
";
mysqli_query($link, $query);
$rows = array();
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
$rows[] = $row;
/* correct match */
if(mysqli_affected_rows($link) == 1)
{
$_SESSION["username"] = $_POST["username"];
$_SESSION["password"] = $_POST["password"];
}
if(isset($_SESSION["username"]) && isset( $_SESSION["password"]))
header("Location:test.php");
else {
alert("Wrong username or password");
}
?>
test.php
<?php
session_start();
// not logged in, not showing this page
if((!isset($_SESSION["username"]) || !isset( $_SESSION["password"]))
header("Location:login.php");
?>
<html>
....whatever you want this page to do
</html>

How can we give email id already exist using php mysql?

Code
<?php
mysql_connect('localhost','root','123456') or die(mysql_error());
mysql_select_db('email') or die(mysql_error());
?>
<?php
if(isset($_POST['submit']))
{
extract($_POST);
$sql=mysql_query("insert into user(name,email)value('$name','$email')");
if($sql)
{
echo '<script>alert("successfull");</script>';
}
else
{
echo '<script>alert("error");</script>';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="" name="form">
<input type="text" name="name" id="name" placeholder="name">
<input type="text" name="email" id="email" placeholder="email">
<input type="submit" name="submit" id="submit">
</form>
</body>
how can we insert data into database without duplicate email id after submit it show alert msg that email id already exist?
thank you
<?php
if(isset($_POST['submit']))
{
extract($_POST);
$query = mysql_query("select * from user where email = '$email'");
$result = mysqli_fetch_assoc($query);
if($result > 0 )
{
echo 'Email already exits';
}
else
{
// code here for insert or what ever you wants
}
}
?>
Firstly the mysql_* functions has been deprecated as of PHP version 5.5.0 and above. So its greatly advised to use mysqli_* functions.
To answer your question, a simple select query along with if statements would do:
$sql="SELECT * FROM users WHERE email = '$email'";
$result = $conn->query($sql);
if($result->num_rows>0){
//Email Already Exists
}
else
{
//Perform Insertion
}
Lastly, its highly recommended to use prepared statements.
First make a select query to check whether on this email and name entry already exist or not.
$SelectSqlQry=mysql_query("select COUNT(email) from user where email = '.$email.'");
$LengthRecords = mysqli_fetch_assoc($SelectSqlQry);
if($LengthRecords > 0) {
//do your alert or anything.
//alert email already exists.
echo '<script>alert("Email Already Exists");</script>';
}
else {
//Insert email..
}
then check your condition on this variable. SelectSqlQry

Phone Number Not Inserted Into Database

I'm creating a simple form, which takes a couple of fields as input, runs some AJAX checks and submits to SQL database via PHP. I'm able to insert all other fields EXCEPT the phone number. Here's a snippet of the codes:
HTML ---
<form name="signupform" id="signupform" onSubmit="return false;">
<div>Phone Number: </div>
<input id="phon" type="text" maxlength="20">
<button id="signupbtn" onClick="signup()">Create Account</button>
<span id="status" style="color: red"></span>
</form>
JS ---
function signup() {
var status = document.getElementById("status");
var phone = document.getElementById("phon").value;
status.innerHTML = phone; //testing, doesn't display anything
var ajax = ajaxObj("POST", "index.php"); // accepted
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "Succesfully signed-up!"){ ///returned from php file
status.innerHTML = ajax.responseText;
}
}
}
ajax.send("phone="+phone); //shoots variable to php
}
PHP ---
if(isset($_POST["phone"])) {
$phone = $_POST['phone'];
echo $phone; //was testing, again, nothing shows
$sql = "INSERT INTO users(phone) VALUES('$phone')";
}
$query2 = mysqli_query($con, $sql);
echo 'successfully_updated';
NOTE: I tried to check if JS and PHP are receiving the phone number, but it's not displaying anything (other form elements such as name and email are displayed, though, tested that already). But later-on, in the PHP code, it isn't showing any error when checked against "if (isset($_POST["phone"])), it inserts the other elements of the form without trouble. No clue why that's happening, any ideas please? My guess is that since JS doesn't reflect the value, that's where the error lies.
Been searching and trying in vain since hours! Any help would be great, thanks!
using jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
phoneNum = $("#phon").val();
$("#signupbtn").click(function(){
$.ajax({url:"./index.php",data:{phone:phoneNum},success:function(result){
alert(result);
}});
});
});
</script>
status.innerHTML = phone; //testing, doesn't display anything
must be
document.getElementById("status").innerHTML = phone;
why not write $query2 = mysqli_query($con, $sql) or die(mysqli_error());
That way, you can see what the error occurs
Please try this
$sql = "INSERT INTO users(phone) VALUES('".$phone."')";

AJAX Call to PHP File for HTML Form Not Working

I have a login-form created using HTML that looks like this:
<div class= "form-header">Login</div>
<div class= "error-message" id= "login-error-exists"></div>
<form action= "login.php" method= "POST" onsubmit= "loginCheckIncorrect()">
<div class= "form-field">
<div class= "form-text">
username:
</div>
<input type= "text" class= "login-textbox" id= "login-login-username" name= "loginLoginUsername">
</div>
<div class= "form-field">
<div class= "form-text">
password:
</div>
<input type= "password" class= "login-textbox" id= "login-login-password" name= "loginLoginPassword">
</div>
<input type= "submit" value= "Login" class= "signup-confirm">
</form>
As you can see, its a simple form that is sent to login.php though POST. Upon submitting this form, it calls a JavaScript (using jQuery) function known as loginCheckIncorrect(), which is shown below:
function loginCheckIncorrect() {
"use strict";
var loginLoginUsername = $("#login-login-username").val(), loginLoginPassword = $("#login-login-password");
alert("test1");
$.post('usernameIncorrect.php', {'loginLoginUsername': loginLoginUsername, 'loginLoginPassword': loginLoginPassword}, function (data) {
$("#login-error-exists").html(data);
alert("test2");
event.preventDefault();
return false;
});
alert("test3");
event.preventDefault();
return false;
}
As you can see, this function creates the variables to store the value of username and password entered in each textbox. It sends an alert out (debugging), and then uses a jQuery.post function to send the variables to the PHP file, which I will show below. It then (is supposed to) takes the data sent back from the PHP file to echo into the error div I have in my HTML form.
It then calls an alert (more debugging) and uses a combination of event.preventDefault() and return false to (supposedly) stop the form from submitting. This is repeated after the post function.
This is my PHP code:
<?php
header("X-XSS-Protection: 1");
include("connect.php");
$username = mysqli_real_escape_string($con, $_POST["loginLoginUsername"]);
$password = mysqli_real_escape_string($con, $_POST["loginLoginPassword"]);
echo "<script>alert('test');</script>";
$sql = mysqli_query($con, "SELECT * FROM main WHERE username='$username' and password='$password'");
$count = mysqli_num_rows($sql);
if ($count == 1) {
echo "";
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
} else {
echo "username and/or password is incorrect.";
}
?>
When I attempt to execute this code, the only alert it displays is test1. Could someone explain to me why this is, and more importantly, how I can fix it? Thanks in advance.
Look at your network requests in your browser's debug panel to see if it's sending what you think it is, put some debug statements in your PHP to see what is and isn't getting hit.
In this case, I think you might be missing the .val() on $('login-login-password') just before the alert("test1") in your javascript.
There is no event defined. That would be a problem and the form will submit. And the preventDefault in the callback is useless since the function already finished.
1) The name of the php file is login.php
2) The url to which you are requesting the post is usernameIncorrect.php
Therefore:
$.post('login.php', {'loginLoginUsername': loginLoginUsername, 'loginLoginPassword': loginLoginPassword}, function (data) {
$("#login-error-exists").html(data);
alert("test2");
event.preventDefault();
return false;
});
Alert test1 is the only one appearing because the post fails.
Probably with a fail event you would have cached the error.
Try, if you want to test that:
$.post('wrongUrl.php', {'loginLoginUsername': loginLoginUsername, 'loginLoginPassword': loginLoginPassword}, function (data) {
$("#login-error-exists").html(data);
alert("test2");
event.preventDefault();
return false;
})
.fail(function() {
alert( "error" );
});

Categories

Resources