Use javascript code in php in function.php file - javascript

I write this code for a login form in function.php file in Wordpress:
$name = $_POST['dx'];
$pass = $_POST['SX'];
$submitbutton= $_POST['commit'];
if ( isset($submitbutton) ) {
if( isset($name) && empty($name) ){
echo '<script> var errorMsg = document.getElementById("errorMsg");
errorMsg.innerHTML = "username is empty";
errorMsg.style.display = "block"; </script>';
}
else if( isset($pass) && empty($pass) ){
$name = "";
$pass = "";
echo '<script> var errorMsg = document.getElementById("errorMsg");
errorMsg.innerHTML = "password is empty";
errorMsg.style.display = "block"; </script>';
}
}
I got an error Cannot read property 'style' of null
HTML code
<div class="login">
<ul class="errorMessages" id="errorMsg">
<li></li>
</ul>
<form method="post" action="">
<p>
<label for="dx">username</label><br>
<input type="text" name="dx" value="" id="dx" maxlength="20">
</p>
<p>
<label for="SX">password</label><br>
<input id="SX" type="password" name="SX" value="" maxlength="30"
class="keyboardInput" vki_attached="true">
</p>
<div class="separator"></div>
<p class="submit">
<input type="submit" name="commit" value="login">
</p>
</form>
</div>
I want to check the form fields, if fields were empty, show the error messege above the form.
Something like this image:
How can I use script code in right way in PHP? and how can I resolve this error?

<div class="login">
<ul class="errorMessages" id="errorMsg">
</ul>
<form method="post" action="">
<p>
<label for="dx">username</label><br>
<input type="text" name="dx" value="" id="dx" maxlength="20">
</p>
<p>
<label for="SX">password</label><br>
<input id="SX" type="password" name="SX" value="" maxlength="30" class="keyboardInput" vki_attached="true"><img src="http://account.taminm.ir/wp-content/uploads/2020/01/keyboard.png" alt="Display virtual keyboard interface" class="keyboardInputInitiator" title="Display virtual keyboard interface">
</p>
<div class="separator"></div>
<p class="submit">
<input type="submit" name="commit" value="login">
</p>
</form>
</div>
<script type="text/javascript">
const loginWrapper = document.querySelector('.login'),
errorContainer = loginWrapper.querySelector('.errorMessages'),
form = loginWrapper.querySelector('form');
form.addEventListener('submit', function(e) {
e.preventDefault();
const username = form.querySelector('#dx').value.trim(),
password = form.querySelector('#SX').value.trim();
if ( !username ) {
errorContainer.innerHTML = 'username is empty';
} else if (!password) {
errorContainer.innerHTML = 'password is empty';
} else {
form.submit()
}
});
</script>

Related

Creating AJAX registration form

I created a registration form following an online tutorial.
The current code doesn't insert anything into a database yet. I am just trying to get the basic error messages working.
When the form is submitted the error message "There was an error" is shown. This comes from my action page where the register button has been pressed.
I am not sure what has caused this.
I know there is a lot of code.
Any help is appreciated.
Main Page(With my form):
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
var forename = $("#txtfirstname").val();
var surname = $("#txtsurname").val();
var username = $("#txtusername").val();
var password = $("#txtpassword").val();
$(".form-message").load("aregisteraction.php", {
forename : forename,
surname : surname,
username : username,
password : password
});
});
});
</script>
</head>
<body>
<?php
require 'leftnav.php';
?>
<div class="two-thirds column">
<h1> Not Registered?</h1>
<h3>Register</h3>
<form method="post" action="aregisteraction.php">
<p>
<label for="txtfirstname" >Firstname: </label> </br>
<input type="text" name="firstname" id="txtfirstname" />
</p>
<p>
<label for="txtsurname" >Surname: </label> </br>
<input type="text" name="surname" id="txtsurname" />
</p>
<p>
<label for="ddage" >Age: </label> </br>
<select name="ddage">
<option value="0">Select a value</option>
<option value="1">0-10</option>
<option value="2">11-30</option>
<option value="3">31-50</option>
<option value="4">51-70</option>
<option value="4">71+</option>
</select>
</p>
<p>
<label >Gender: </label> </br>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
</p>
<p>
<label for="txtusername" >Email: </label> </br>
<input type="text" name="username" id="txtusername" />
</p>
<p>
<label for="txtpassword" >Password: </label> </br>
<input type="password" name="password" id="txtpassword" />
</p>
<p>
<label for="txtpassword1" >Re-enter Password: </label> </br>
<input type="password" name="password1" id="txtpassword1" />
</p>
<input type="submit" name="register" value="Register" />
<p class="form-message"></p>
</form>
Action Page:
<?php
if(isset($_POST['register'])){
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$username = $_POST['username'];
$password = $_POST['password'];
$errorEmpty = false;
$errorEmail = false;
if(empty($forename)||empty($surname)||empty($username)||empty($password)){
echo "<span> Fill in all fields </span>";
$errorEmpty = true;
}
elseif (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'> Fill in a valid email </span>";
$errorEmail = true;
}
else{
echo "<span class='form-success'> Success </span>";
}
}
else{
echo "There was an error!";
}
?>
<script>
$("#txtfirstname, #txtsurname, #txtusername, #txtpassword").removeClass("input-error");
var errorEmpty ="<?php echo $errorEmpty; ?>";
var errorEmail ="<?php echo $errorEmail; ?>";
if(errorEmpty == true){
$("#txtfirstname, #txtsurname, #txtusername, #txtpassword").addClass("input-error");
}
if(errorEmail == true){
$("#txtusername").addClass("input-error");
}
if(errorEmail == false && errorEmpty == false){
$("#txtfirstname, #txtsurname, #txtusername, #txtpassword").val("");
}
</script>
In your JavaScript you doesn't send any value for register.
Two options: add a value to register:
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
var forename = $("#txtfirstname").val();
var surname = $("#txtsurname").val();
var username = $("#txtusername").val();
var password = $("#txtpassword").val();
$(".form-message").load("aregisteraction.php", {
forename : forename,
surname : surname,
username : username,
password : password,
register: "ok",
});
});
});
Or simply test $_POST on another field (as register is a button and will always contains a value in the form).
Also, to test values of your form in PHP you can user print_r():
print_r($_POST);

onSubmit redirect to website depenfing on value

Hi I'm trying to create a simple login form with 2 or 3 users where depending on who is logging in the redirect should be to different urls.
My code so far:
HTML
<h1 class="title">Logga in</h1>
<div class="grid__container">
<form name="login" onSubmit="return validateForm();" action="some website url" method="post" class="form form--login">
<div class="form__field">
<label class="fontawesome-user" for="login__username"><span class="hidden">Username</span></label>
<input name="usernameInput" id="login__username" type="text" class="form__input" placeholder="Username" required>
</div>
<div class="form__field">
<label class="fontawesome-lock" for="login__password"><span class="hidden">Password</span></label>
<input name="passwordInput" id="login__password" type="password" class="form__input" placeholder="Password" required>
</div>
<div class="form__field">
<input type="submit" value="Sign In">
</div>
</form>
</div>
JavaScript
function validateForm() {
var username = document.login.usernameInput.value;
var password = document.login.passwordInput.value;
var username1 = "user 1";
var password1 = "1234";
var username2 = "user 2";
var password2 = "4321";
if ((username == username1) && (password == password1)){
return "www.google.se";
}else if (username == username2) && (password == password2) {
return "www.facebook.se";
}else{
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}

jquery fadeIn and fadeOut not working before click

i have one form like this.
<form method="post" action="contact-post.php" id="contact_form" name="contactForm">
<div class="left_form">
<div>
<span><label>NAME</label></span>
<div id='name_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="name" id="name" type="text" class="textbox"></span>
</div>
<div>
<span><label>E-MAIL</label></span>
<div id='email_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="email" id="email" type="text" class="textbox" required></span>
</div>
<div>
<span><label>PHONE</label></span>
<div id='phone_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="phone" id="phone" type="text" class="textbox"></span>
</div>
</div>
<div class="right_form">
<div>
<span><label>SUBJECT</label></span>
<div id='message_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><textarea name="message" id="message" required> </textarea></span>
</div>
<div id='mail_success' class='success' style="background-color:#BFD6BF;text-align:center;margin-bottom:5px;">Your message has been sent successfully.</div>
<div id='mail_fail' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Sorry, error occured this time sending your message.</div>
<div id="submit">
<span><input type="submit" id="send_message" name="submit" value="Submit" class="myButton"></span>
</div>
</div>
</form>
and i call one .js file for it is.
$(document).ready(function(){
$('#send_message').click(function(e){
//Stop form submission & check the validation
e.preventDefault();
// Variable declaration
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#phone').val();
var message = $('#message').val();
// Form field validation
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#phone_error').fadeIn(500);
}else{
$('#phone_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
// If there is no validation error, next to process the mail function
if(error == false){
// Disable submit button just after the form processed 1st time successfully.
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
$.post("contact-post.php", $("#contact_form").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
//If the email is sent successfully, remove the submit button
$('#submit').remove();
//Display the success message
$('#mail_success').fadeIn(500);
}else{
//Display the error message
$('#mail_fail').fadeIn(500);
// Enable the submit button again
$('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
and one contact-post.php file is.
<?php
include('config.php');
if (isset($_POST['submit'])) {
$name=$_POST['name'];
$mail=$_POST['email'];
$phone=$_POST['phone'];
$msg=$_POST['message'];
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
test_input($name);
$query="INSERT INTO `inquiry` (id,name,contact,email,query) values ('','$name','$phone','$mail','$msg')";
$qur=mysql_query($query);
if ($qur) {
echo 'sent';
}
else {
echo 'failed';
}
}
?>
my problem is when i refresh page it's displaying like this.
i want that all message should not display before clicking submit button.please help me.
Update (adding snippet) :
.error , .success
{
display:none;
}
<form method="post" action="contact-post.php" id="contact_form" name="contactForm">
<div class="left_form">
<div>
<span><label>NAME</label></span>
<div id='name_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="name" id="name" type="text" class="textbox"></span>
</div>
<div>
<span><label>E-MAIL</label></span>
<div id='email_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="email" id="email" type="text" class="textbox" required></span>
</div>
<div>
<span><label>PHONE</label></span>
<div id='phone_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="phone" id="phone" type="text" class="textbox"></span>
</div>
</div>
<div class="right_form">
<div>
<span><label>SUBJECT</label></span>
<div id='message_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><textarea name="message" id="message" required> </textarea></span>
</div>
<div id='mail_success' class='success' style="background-color:#BFD6BF;text-align:center;margin-bottom:5px;">Your message has been sent successfully.</div>
<div id='mail_fail' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Sorry, error occured this time sending your message.</div>
<div id="submit">
<span><input type="submit" id="send_message" name="submit" value="Submit" class="myButton"></span>
</div>
</div>
</form>
You can do one of the following :
Set the error and success classes display to none, since they will be displayed using the fadeIn function.
.error , .success
{
display:none;
}
Or
You can hide the <div>s with jQuery on load as follows :
$(document).ready(function(){
$('.error , .success').hide();
.....
});
I guess the first solution would be a better approach since the elements will not view at all since CSS loads before JS (assuming that this is the order you are loading your files with), while in the second approach the elements will be visible until jQuery loads and hides them.
Add a style as below to hide the error/success messages.
#mail_fail, #mail_success{
display : none;
}

Two form on a single page : How to identify which form validate using jquery ajax function

I have a html page which contains
a form with fields for sign up (registration / new member)
a form for sign in (login for already member)
The sign in form is :
<form class="dialog-form">
<div class="form-group">
<label>E-mail</label>
<input type="text" placeholder="email#domain.com" class="form-control">
</div>
<div class="form-group">
<label>PAssword</label>
<input type="password" placeholder="My PAssword" class="form-control">
</div>
<input type="submit" name="sign_in" value="Connexion" class="btn btn-primary">
</form>
The sign up form is :
<form class="dialog-form" action="bat/user_validation.php" method="post">
<div class="form-group">
<label>E-mail</label>
<input type="text" placeholder="email#domain.com" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" placeholder="My secret password" class="form-control">
</div>
<div class="form-group">
<label>Repeat Password</label>
<input type="password" placeholder="Type your password again" class="form-control">
</div>
<input type="submit" name="sign_up" value="Inscription" class="btn btn-primary">
</form>
One the other side, I have a php script file which contains function to check and insert a userid.
function getPassword($utilisateur) {
try {
$dbh = new PDO(DSN, USER, PASS);
$uid = $utilisateur;
$sql = "SELECT password FROM cc_users WHERE uid =:uid";
$sth = $dbh->prepare($sql);
$sth->execute(array(':uid'=>$uid));
$result = $sth->fetchAll();
return (count($result) == 1) ;
} catch (PDOException $e) {
print "Erreur ! : " . $e->getMessage() . "<br/>";
die();
}
}
function setPassword($uid, $pass) {
$dbh = new PDO(DSN, USER, PASS);
$sql = "UPDATE cc_users SET password =:pass where uid =:uid";
$sth = $dbh->prepare($sql);
$sth->execute(array(':pass'=>$pass ,':uid'=>$uid));
echo $count = $sth->rowCount();
return $dbh->exec($sql);
}
function newPassword($utilisateur, $pass) {
$crypt = crypt($pass);
return setPassword($utilisateur, $crypt);
}
function checkPassword($utilisateur, $pass) {
if (empty($pass)) return FALSE;
$interne = getPassword($utilisateur);
$crypt = crypt($pass, $interne);
return ($interne === $crypt);
}
print_r($_POST);
My questions are :
How I can check on which form the user is coming?
How can I do an $.ajax call for checking the form? If yes how?
Thanks
HTML:
Form 1:
<form id="form1">
<input type="submit" value="submit" />
</form>
Form 2:
<form id="form2">
<input type="submit" value="submit" />
</form>
jQuery:
$('form').on('submit', function () {
console.log($(this).attr('id')); // Logs the id of the submitted form
});
Give name for <form>
<form class="dialog-form" name="signin">
<form class="dialog-form" action="bat/user_validation.php" method="post" name="signup">
You can check $_POST global to see if it contains the name of your <input type="submit" />. It will contain either sign_up or sign_in, depending on what button did the user press.
For example:
if(isset($_POST['sign_up']){
$signingUp = true;
}
If you want to submit the form using jQuery ajax, you can use the following code snippet:
$.post('bat/user_validation.php', $('form.dialog-form').serialize());
Though the selector should be more concrete, probably including a form ID to distinguish between the two forms.

Div Not Floating Right Or Being inline with title

I want it so that when all the input fields are filled, the button automatically enables again but i am finding it hard to do so. I am using php to check the fields and html to enable/disable the button
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="main.css">
</head>
<body>
<?php
$required = array('FName', 'LName', 'Email', 'Subject', 'Comments');
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
else{
$error = false;
}
}
if ($error) {
} else {
}
?>
<div class="ContentBox" style="width:auto;">
<h1 class="Title">Contact Us</h1>
<div class="contact_form">
<form method="post" action="ThankYou.php">
<div id="contact_left">
<p>First Name: </p>
<input class="TextBox" type="text" name="FName">
<p>Last Name: </p>
<input class="TextBox" type="text" name="LName">
<p id="HText">Email: (?)<span id="HSpan">Only For Verification Purposes</span></p>
<p><input class="TextBox" type="email" name="Email"></p>
<p style="text-align:center;"><input class="Button_s" name="submit" type="submit value="Submit" id="submit" disabled="disabled"></p>
</div>
<div id="contact_right">
<p>Subject: </p>
<input class="TextBox" type="text" name="Subject">
<p>Comments: </p>
<textarea id="content" rows="10" cols="40" name="Comments"></textarea>
</div>
</form>
</div>
</div>
<?php
function check_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
PHP code will be processed only in server side. PHP can process the input only after the user clicks the submit button.
You should use javascript in this scenario.
It is possible to use only HMTL and CSS to enable the "submit" button when all the fields are filled: http://jsfiddle.net/du97k26u/.
HTML:
<form method = "post">
<input type = "text" placeholder = "First Name" required />
<input type = "text" placeholder = "Last Name" required />
<input type = "submit" value = "Process" />
</form>
CSS:
form > input {
display: block;
}
form > input:invalid ~ input[type = "submit"] {
display: none;
}

Categories

Resources