PHP, HTML, Ajax Form issue - 500 Internal Server Error - javascript

Anyone knows what is wrong here?
Keep getting 500 Internal Server Error. -
"NetworkError: 500 Internal Server Error - http:// sitename /validationengine.php"
Somehow I guess it's something wrong with the php-code. Everything with the validation works until it's time for the send.
HTML
<form id="competition_form" accept-charset="UTF-8" enctype="multipart/form-data" method="post" name="val_form" action="validationengine.php">
<fieldset>
<div id="page1_form" class="pages_form">
<p>Line1</p><br>
<input type="checkbox" name="quest" class="quest_group" value="1"><span class="nr_checkboxes">1. </span>
<label for="quest">labeltext 1</label><br>
<input type="checkbox" name="quest" class="quest_group" value="x"><span class="nr_checkboxes">X. </span>
<label for="quest">labeltext X</label><br>
<input type="checkbox" name="quest" class="quest_group" value="2"><span class="nr_checkboxes">2. </span>
<label for="quest">labeltext 2</label><br>
<p>Text</p>
<textarea name="motivering" rows="4" cols="66" maxlength="100"></textarea>
</div>
<div id="page2_form" class="pages_form">
<input type="checkbox" name="prize_check" value="win 1">
<label for="prize_check">Win 1</label><br>
<input type="checkbox" name="prize_check" value="win 2">
<label for="prize_check">Win 2</label><br>
<div class="full_input input_blocks">
<label for="namn">Namn:</label>
<input type="text" name="namn" maxlength="100" value="" />
<span id="namn_error" class="error">Du måste skriva in ditt namn.</span>
</div>
<div class="full_input input_blocks">
<label for="adress">Adress:</label>
<input type="text" name="adress" maxlength="100" value="" />
<span id="adress_error" class="error">Du måste skriva in din adress.</span>
</div>
<div class="half_input input_blocks">
<label for="postnr">Postnr:</label>
<input type="text" name="postnr" maxlength="50" value="" />
<span id="postnr_error" class="error">Du måste skriva in ditt postnummer.</span>
</div>
<div class="half_input input_blocks">
<label for="ort">Ort:</label>
<input type="text" name="ort" maxlength="50" value="" />
<span id="ort_error" class="error">Du måste skriva in din bostadsort.</span>
</div>
<div class="half_input input_blocks">
<label for="email">Mejl:</label>
<input type="text" name="email" maxlength="50" value="" />
<span id="email_error" class="error">Du måste skriva in din mejl-adress.</span>
</div>
<div class="half_input input_blocks">
<label for="mobil">Mobil:</label>
<input type="text" name="mobil" maxlength="50" value="" />
<span id="mobil_error" class="error">Du måste skriva in ditt telefonnummer</span>
</div>
<div id="rules_box">
<input type="checkbox" name="rules_check" value="Tävlingsvillkor godkända">
<label for="rules_check">Jag har läst och godkänner <b>tävlingsvillkoren</b></label><br>
<span id="rules_error" class="error">Du måste godkänna tävlingsvillkoren för att tävla.</span>
</div>
<input type="submit" name="submit" value="" class="submit-button" id="submit_btn" />
</div>
</fieldset>
</form>
JS
$(function() {
$('.error').hide();
$("input[name='email']").onchange=function(){$('.error').hide();};
$("input[name='email']").click(function() {
$('.error').hide();
});
$(".submit-button").click(function() {
var form = $('#competition_form');
var name = $("input[name='namn']").val();
var adress = $("input[name='adress']").val();
var postnr = $("input[name='postnr']").val();
var ort = $("input[name='ort']").val();
var email = $("input[name='email']").val();
var mobil = $("input[name='mobil']").val();
var rules = $("input[name='rules_check']").is(':checked');
$('.error').hide();
if (name == "") {
$("#namn_error").show();
return false;
}
if (adress == "") {
$("#adress_error").show();
return false;
}
if (postnr == "") {
$("#postnr_error").show();
return false;
}
if (ort == "") {
$("#ort_error").show();
return false;
}
if (email == "" || !isValidEmailAddress( email ) ) {
$("#email_error").show();
return false;
}
if (mobil == "") {
$("#mobil_error").show();
return false;
}
console.log(rules);
if (!rules) {
$("#rules_error").show();
return false;
}
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType:'html',
success: function(data) {
$('#thankyou_pop').fadeIn(500);
},
error: function(data) {
//AJAX request not completed
}
});
return false;
});
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
PHP
<?php
if( isset($_POST) ){
// validation
$validationOK=true;
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
$EmailTo = "example#example.com";
$Subject = "Nytt Tävlingsbidrag";
$quest = "";
if (isset($_POST['quest'])) {
$answer = Trim(stripslashes($_POST['quest']));
if($answer == 1) {
$quest = "Rätt svar";
} else {
$quest = "Fel svar";
}
}
if($quest == "") {
$quest = "Inget svar";
}
$motivering = Trim(stripslashes($_POST['motivering']));
if ($motivering == "") {
$motivering = "Ingen motivering";
}
$vinst = "";
if (isset($_POST['prize_check'])) {
$win_answer = Trim(stripslashes($_POST['prize_check']));
if ($win_answer == "") {
$vinst = "Ingen vinst vald"
} else {
$vinst = $win_answer;
}
}
$namn = Trim(stripslashes($_POST['namn']));
$adress = Trim(stripslashes($_POST['adress']));
$postnr = Trim(stripslashes($_POST['postnr']));
$ort = Trim(stripslashes($_POST['ort']));
$Email = Trim(stripslashes($_POST['email']));
$mobil = Trim(stripslashes($_POST['mobil']));
$villkor = Trim(stripslashes($_POST['rules_check']));
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
} else {
// prepare email body text
$headers = "Berocca Boost Tävlingsbidrag" . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$Body = "<h3>Nytt Tävlingsbidrag</h3>
<p><strong>Fråga: </strong> {$quest} </p>
<p><strong>Motivering: </strong> {$motivering} </p>
<p><strong>Föredragen vinst: </strong> {$vinst} </p>
<p><strong>Namn: </strong> {$namn} </p>
<p><strong>Adress: </strong> {$adress} </p>
<p><strong>Postnr: </strong> {$postnr} </p>
<p><strong>Ort: </strong> {$ort} </p>
<p><strong>E-mail: </strong> {$Email} </p>
<p><strong>Mobil: </strong> {$mobil} </p>
<p><strong>Villkor accepterade: </strong> {$villkor} </p>
<br>
<p>IP address: {$ipaddress} Date: {$date} Time: {$time}</p>";
// send email
mail($EmailTo, $Subject, $Body, $headers);
}
}
?>

$vinst = "";
if (isset($_POST['prize_check'])) {
$win_answer = Trim(stripslashes($_POST['prize_check']));
if ($win_answer == "") {
$vinst = "Ingen vinst vald" //<====== (Missing semi-colon ";")
} else {
$vinst = $win_answer;
}
}

You have made a typo error. Missed a semicolon.
if ($win_answer == "")
{
$vinst = "Ingen vinst vald"
^^^ // Missing semicolon
}
else
{
$vinst = $win_answer;
}

Related

Login Form- Not working if else statements

I cant get my login form to work with the separate logins, the preview wont event show up. I think there is something wrong with my if-else statements.
HTML:
<body ng-app="myApplication" ng-controller="myController" ng-cloak>
<h3>Contact Us</h3>
<div id="showDiv" ng-show="firstPage">
<form>
<label for="name">Name:</label>
<input type="text" placeholder="Enter your name" ng-model="name"><br>
<label for="email">Email:</label>
<input type="email" placeholder="Enter your email" ng-model="email"><br>
<label for="number">Number:</label>
<input type="number" placeholder="Enter your number" ng-model="phoneNumber"><br>
<label for="issue">Issue:</label>
<textarea name="issue" rows="5" cols="20" placeholder="Enter your issue" ng-model="issue"></textarea>
<br>
<br>
<input type="submit" value="Submit" id="submit" ng-click="showHide()">
<input type="reset" value="Reset" id="reset">
</form>
</div>
<div id="hideDiv" ng-show="secondPage">
<p ng-bind="feedback"></p>
<p>Your contact details are:</p>
<p>Email: <span ng-bind='email'></span></p>
<p>Phone Number: <span ng-bind='phoneNumber'></span></p>
<p>Your issue is:</p>
<p><span ng-bind='issue'></span></p>
<input type="submit" value="Go Back" id="goBack" ng-click="hideShow()" />
</div>
Javascipt:
<script>
angular.module('myApplication', []).controller('myController', function($scope){
$scope.name = "";
$scope.email = "";
$scope.phoneNumber = "";
$scope.issue = "";
$scope.firstPage = true;
$scope.secondPage = false;
$scope.showHide = function()
{
$scope.firstPage = false;
$scope.secondPage = true;
$scope.feedback = "";
if ($scope.name = "Po Lu" && $scope.email = "Po.Tom#acc.ac.au" && $scope.phonenumber = "021") {
$scope.feedback = "Thanks for contacting, " + $scope.name + ". We're working to fix your issue already." ;
}
else if ($scope.name == "Mel Tom" && $scope.email = "Mel.Tom#acc.ac.au" && $scope.phonenumber = "0217") {
$scope.feedback = "Thanks for contacting, " + $scope.name + ". We're working to fix your issue already." ;
}
else {
$scope.firstPage = true;
$scope.secondPage = false;
alert("Please Enter valid details");
}
}
$scope.hideShow = function()
{
$scope.firstPage = true;
$scope.secondPage = false;
$scope.name = "";
$scope.email = "";
$scope.phoneNumber = "";
$scope.issue = "";
}
});
</script>
Below are the mistakes made.
inside the if conditions, we should never use assignment =, but use conditional operators such as == or ===(strict type checking!)
Number type input won't allow zeros in the beginning, so I changed it from "021" to "21"
phoneNumber variable is set to phoneNumber in html, but in js its phonenumber so I changed it!
Finally I'm using double equals inside the if condition,so that type won't be an issue, we can compare number to string, if you want you can strictly check the types!
angular.module('myApplication', []).controller('myController', function($scope) {
$scope.name = "";
$scope.email = "";
$scope.phoneNumber = "";
$scope.issue = "";
$scope.firstPage = true;
$scope.secondPage = false;
$scope.showHide = function() {
$scope.firstPage = false;
$scope.secondPage = true;
$scope.feedback = "";
if ($scope.name == "Po Lu" && $scope.email == "Po.Tom#acc.ac.au" && $scope.phoneNumber == "21") {
$scope.feedback = "Thanks for contacting, " + $scope.name + ". We're working to fix your issue already.";
} else if ($scope.name == "Mel Tom" && $scope.email == "Mel.Tom#acc.ac.au" && $scope.phoneNumber == "217") {
$scope.feedback = "Thanks for contacting, " + $scope.name + ". We're working to fix your issue already.";
} else {
$scope.firstPage = true;
$scope.secondPage = false;
alert("Please Enter valid details");
}
}
$scope.hideShow = function() {
$scope.firstPage = true;
$scope.secondPage = false;
$scope.name = "";
$scope.email = "";
$scope.phoneNumber = "";
$scope.issue = "";
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.7/angular.min.js"></script>
<div ng-app="myApplication" ng-controller="myController" ng-cloak>
<h3>Contact Us</h3>
<div id="showDiv" ng-show="firstPage">
<form>
<label for="name">Name:</label>
<input type="text" placeholder="Enter your name" ng-model="name"><br>
<label for="email">Email:</label>
<input type="email" placeholder="Enter your email" ng-model="email"><br>
<label for="number">Number:</label>
<input type="number" placeholder="Enter your number" ng-model="phoneNumber"><br>
<label for="issue">Issue:</label>
<textarea name="issue" rows="5" cols="20" placeholder="Enter your issue" ng-model="issue"></textarea>
<br>
<br>
<input type="submit" value="Submit" id="submit" ng-click="showHide()">
<input type="reset" value="Reset" id="reset">
</form>
</div>
<div id="hideDiv" ng-show="secondPage">
<p ng-bind="feedback"></p>
<p>Your contact details are:</p>
<p>Email: <span ng-bind='email'></span></p>
<p>Phone Number: <span ng-bind='phoneNumber'></span></p>
<p>Your issue is:</p>
<p><span ng-bind='issue'></span></p>
<input type="submit" value="Go Back" id="goBack" ng-click="hideShow()" />
</div>
</div>

How to select a radio button in PHP

I have my PHP file included in my views for AJAX.
So my problem is that when I try to select the radio inputs with their values I instead get my else statement. I also have my additional CSS and Javascript, but I don't think they are causing the value. It looks like radio buttons may not be made for PHP so if I may not find a solution then maybe I should try to convert them into a checkbox.
Edit: I have managed to get the result of the post and it's returning: [object OBJECT]
Is there a way to get the value of my checked radios for the player account?
Radio's PHP
$usernameError = "";
$passwordError = "";
$termsandconditionsError = "";
$playAccount = "";
$creatorAccount = "";
$account = "";
$error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$usernameError = "Username is required.";
echo $usernameError;
} else {
$username = signupform_input($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordError = " Password is required.";
echo $passwordError;
} else {
$password = signupform_input($_POST["password"]);
}
if(!empty($_POST['account'])) {
$playAccount = $_POST['account'];
}
if(!empty($_POST['creatorAccount'])) {
$creatorAccount = $_POST['creatorAccount'];
}
if(isset($_POST['account'])) {
if(!empty($_POST['account'] || $_POST['creatorAccount'])) {
$account = $_POST['account'].', '.$_POST['creatorAccount'];
}
}
if(isset($_POST['loginActive'])) {
if($_POST['loginActive'] == "0" && $usernameError == "" && $passwordError == "" && $termsandconditionsError == "") {
$query = "SELECT * FROM users WHERE username = '". mysqli_real_escape_string($link, $_POST['username'])."' LIMIT 1";
$result = mysqli_query($link, $query);
if(mysqli_num_rows($result) > 0) {
$error = "That username is already taken.";
echo $error;
} else {
echo "<p style='color: green'>Hi</p>";
$query = "INSERT INTO `users` (`username`, `password`, `plan`) VALUES ('". mysqli_real_escape_string($link, $_POST['username'])."', '". mysqli_real_escape_string($link, $_POST['password'])."', '". mysqli_real_escape_string($link, $account)."')";
echo $query;
}
}
}
}
Form
<div class="container" style="margin: 50px;">
<form method="post" id="signupForm" class="signupForm">
<h2>Signup</h2>
<input type="hidden" name="loginActive" id="loginActive" value="0">
<br>
<div class="form-group row">
<label for="username" class="col-lg-16 col-form-label">Username:</label>
<div class="col-lg-8">
<input type="text" class="form-control signupInput" name="username" id="username" aria-describedby="username" autocomplete="username" autofocus required>
</div>
<p><span class="error"><?php echo $usernameError;?></span><p>
</div>
<div class="form-group row">
<label for="password" class="col-lg-16 col-form-label">Password:</label>
<div class="col-lg-8">
<input type="password" class="form-control signupInput" id="Password" name="password" autocomplete="current-password" required>
</div>
<p><span class="error"><?php echo $passwordError;?></span><p>
</div>
<h4>Account Type <i class="far fa-question-circle info" data-toggle="tooltip" data-placement="right" title="Whenever you have all free accounts checked, payment method should be hidden, but if not then click on any paid account and then click back!" height="16px"></i></h4>
<p>Visit Plan for pricing details.</p>
<input type="radio" id="freePlayerAccount" class="free playAccount" name="account" value="1" checked>
<label for="freePlayerAccount">Player: Free Account $0.00/Mo</label><br>
<input type="radio" id="proPlayerAccount" class="paid playAccount" name="account" value="2">
<label for="proPlayerAccount">Player: Pro Account $5.99/Mo</label><br>
<input type="radio" id="premiumPlayerAccount" class="paid playAccount" name="account" value="3">
<label for="premiumPlayerAccount">Player: Premium Account $9.99/Mo</label><br>
<hr>
<input type="radio" id="creatorFreeAccount" class="creatorAccount" name="creatorAccount" value="4" class="free">
<label for="creatorFreeAccount">Creator: Free Account $0.00/Mo</label><br>
<input type="radio" id="creatorProAccount" class="paid creatorAccount" name="creatorAccount" value="5">
<label for="creatorProAccount">Creator: Pro Account $9.99/Mo</label><br>
<input type="radio" id="creatorPremiumAccount" class="paid creatorAccount" name="creatorAccount" value="6">
<label for="creatorPremiumAccount">Creator: Premium Account $14.99/Mo</label><br>
<hr>
<div class="hiddenPaymentMethod"> <h5>Payment Method</h5>
<input type="radio" id="Paypal" name="payment" value="Paypal" class="payment">
<label for="Paypal">Paypal</label><br>
<input type="radio" id="creditCard" name="payment" value="CreditCard" class="payment">
<label for="creditCard">Credit Card</label><br>
<input type="text" style="display:none;" name="creditCardNumber" id="creditCardNumber" placeholder="Card Number">
<input type="radio" id="debitCard" name="payment" value="DebitCard" class="payment">
<label for="debitCard">Debit Card</label>
<input type="text" style="display:none;" name="debitCardNumber" id="debitCardNumber" placeholder="Card Number">
<br></div>
<br>
<input type="checkbox" id="termsAndConditions" class="conditions" name="termsandconditions" value="0">
<label for="termsAndConditions"> I have read and agreed to the Terms and Conditions <span data-toggle="modal" data-target="#exampleModal"><i class="far fa-question-circle questionMark"></i></span></label>
<p id="errors"></p>
<p id="tacError" style="color:red"></p>
<input type="button" class="btn btn-primary" name="signupButton" id="signUpButton" value="Submit">
</form>
</div>
Jquery
$("#signUpButton").click(function() {
$.ajax({
type: "POST",
url: "actionSignUp.php",
data: "username=" + $("#username").val() + "&password=" + $("#Password").val() + "&termsandconditions=" + $("#termsAndConditions").val() + "&account=" + $(".playAccount") + "&creatorAccount=" + $(".creatorAccount") + "&loginActive=" + $("#loginActive").val()
}).done(function(result) {
$("#errors").html(result);
}).fail(function(xhr, textStatus, errorThrown) {
alert("Error Requesting. Please Try Again Later.");
});
});
$('input:checkbox').change(
function(){
if ($(this).is(':checked')) {
$(this).val("1");
} else {
$(this).val("0");
}
});
$("#signUpButton").click(function(){
if($(".conditions").val() == "0") {
$("#tacError").html("Terms and Conditions are required");
} else {
$("#tacError").html("");
}
})
$('input:radio[name="account"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == '2') {
$(".hiddenPaymentMethod").show();
}
});
$('input:radio[name="account"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == '3') {
$(".hiddenPaymentMethod").show();
}
});
$('input:radio[name="account"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == '1') {
$(".hiddenPaymentMethod").hide();
$("#Paypal").removeAttr('checked');
}
});
$('input:radio[name="creatorAccount"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == '6') {
$(".hiddenPaymentMethod").show();
$("#Paypal").attr('checked', 'checked');
}
});
$('input:radio[name="creatorAccount"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == '5') {
$(".hiddenPaymentMethod").show();
$("#Paypal").attr('checked', 'checked');
}
});
$('input:radio[name="account"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == '2') {
$("#Paypal").attr('checked', 'checked');
}
});
$('input:radio[name="account"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == '3') {
$("#Paypal").attr('checked', 'checked');
}
});
$('input:radio[name="payment"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == 'CreditCard') {
$("#creditCardNumber").show();
}
});
$('input:radio[name="payment"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == 'Paypal' || $(this).val() == 'DebitCard') {
$("#creditCardNumber").hide();
}
});
$('input:radio[name="payment"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == 'DebitCard') {
$("#debitCardNumber").show();
}
});
$('input:radio[name="payment"]').change(
function(){
if ($(this).is(':checked') && $(this).val() == 'Paypal' || $(this).val() == 'CreditCard') {
$("#debitCardNumber").hide();
}
});
$(function () {
$('[data-toggle="tooltip"]').tooltip();
})
In your AJAX call posting data is wrong way for params account and creatorAccount:
data: "username=" + $("#username").val() + "&password=" + $("#Password").val() + "&termsandconditions=" + $("#termsAndConditions").val() + "&account=" + $(".playAccount:checked").val() + "&creatorAccount=" + $(".creatorAccount:checked").val() + "&loginActive=" + $("#loginActive").val()
Instead of
data: "username=" + $("#username").val() + "&password=" + $("#Password").val() + "&termsandconditions=" + $("#termsAndConditions").val() + "&account=" + $(".playAccount") + "&creatorAccount=" + $(".creatorAccount") + "&loginActive=" + $("#loginActive").val()

Why the output from javascript just shown for a short period of time?

I am developing a Registration form for my assignment. All things are working but when I click on the submit button, the warning messages on the label are just shown for a very short period of time. I am using eclipse and apache tomacat. here is my code.
JSP Code:
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid"/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname"/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname"/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email"/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" onclick="validate()"/>
</form>
Javascript Code:
function validate()
{
var itemid=document.getElementById("itemid").value;
var itemname=document.getElementById("itemname").value;
var uname=document.getElementById("uname").value;
var email=document.getElementById("email").value;
var amount=document.getElementById("amount").value;
var autoincrement=document.getElementById("autoincrement");
var flag=true;
if(itemid.length==0){
flag=false;
document.getElementById("itemid_l").innerHTML="<b>Required field!</b> Item Id: ";
}
if(itemname.length==0){
flag=false;
document.getElementById("itemname_l").innerHTML="<b>Required field!</b> Item Name: ";
}
if(uname.length==0){
flag=false;
document.getElementById("uname_l").innerHTML="<b>Required field!</b> Your Name: ";
}
if(email.length==0){
flag=false;
document.getElementById("email_l").innerHTML="<b>Required field!</b> Your Email Address: ";
}
if(amount.length==0){
flag=false;
document.getElementById("amount_l").innerHTML="<b>Required field!</b> Amount Bid: ";
}
if(!autoincrement.checked){
flag=false;
document.getElementById("autoincrement_l").innerHTML="<b>Required field!</b> Auto-increment to match other bidders:: ";
}
if(flag==true){
alert('Good job!!');
return true;
}
else
{
document.getElementById("msg").innerHTML="Required data is missing. Please fill";
return false;
}
}
Any suggestion will help me a lot..
You can use onsubmit event so that whenever user click on submit button this gets call and if the function validate() return true form will get submitted else it will not submit form .
Demo code :
function validate() {
var itemid = document.getElementById("itemid").value;
var itemname = document.getElementById("itemname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var amount = document.getElementById("amount").value;
var autoincrement = document.getElementById("autoincrement");
var flag = true;
if (itemid.length == 0) {
flag = false;
document.getElementById("itemid_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemid_l").innerHTML = ""
}
if (itemname.length == 0) {
flag = false;
document.getElementById("itemname_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemname_l").innerHTML = "";
}
if (uname.length == 0) {
flag = false;
document.getElementById("uname_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("uname_l").innerHTML = "";
}
if (email.length == 0) {
flag = false;
document.getElementById("email_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("email_l").innerHTML = "";
}
if (amount.length == 0) {
flag = false;
document.getElementById("amount_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("amount_l").innerHTML = "";
}
if (!autoincrement.checked) {
flag = false;
document.getElementById("autoincrement_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("autoincrement_l").innerHTML = "";
}
if (flag == true) {
document.getElementById("msg").innerHTML = "";
alert('Good job!!');
flag = true; //do true
} else {
document.getElementById("msg").innerHTML = "Required data is missing. Please fill";
flag = false; //do false
}
return flag; //return flag
}
<!--add onsubmit -->
<form method="post" id="forms" onsubmit="return validate()">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--give id to span instead of label-->
<label> <span id="itemid_l"></span>Item Id:</label> <input type="text" name="itemid" id="itemid" /><br/>
<label><span id="itemname_l"></span>Item Name:</label> <input type="text" name="itemname" id="itemname" /><br/>
<label><span id="uname_l"></span>Your Name:</label> <input type="text" name="uname" id="uname" /><br/>
<label><span id="email_l"></span>Your Email Address:</label> <input type="text" name="email" id="email" /><br/>
<label><span id="amount_l"></span>Amount Bid:</label> <input type="number" name="amount" id="amount" /><br/>
<label><span id="autoincrement_l"></span>Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" />
</form>
Also , if you just need to check for empty field you can just use required attribute on input tag like below :
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--added required attribute-->
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid" required/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname" required/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname" required/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email" required/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"required/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement" required><br/>
<input type="submit" value="Submit Bid"/>
</form>

document.getElementById in amp-script code giving element data differently

I am using AMP to develop my website. In that, I am using amp-script. When I use document.getElementById, it is giving the element data differently. I am looking for some properties like value etc. in it. But, can't those. See the below screenshot to look at the contents.
Please help me solve this.
Thank you...
EDIT: Added code snippet
HTML:
<form action="click" target="_blank" name="contact_form" id="contact_form" class="contact-form__block">
<div class="form__group">
<label for="message" class="form__label message_label">The idea that is brewing in your mind?
*</label>
<textarea name="message" id="form__textarea" class="form__textarea"></textarea>
</div>
<div class="form__group">
<label for="name" class="form__label name_label">Name </label>
<input type="text" name="name" id="form__name" class="form__input name" value="" autocomplete="off">
</div>
<div class="form__groups">
<div class="form__group">
<label for="phone" class="form__label phone_label">Phone Number </label>
<input type="text" name="phone" id="form__phone" class="form__input phone" value=""
autocomplete="off">
<!-- error message start -->
<!-- <div class="form__error e_mail">Please enter all required details.</div> -->
<!-- error message end -->
</div>
<div class="form__group">
<label for="mail" class="form__label email_label">Email *</label>
<input type="text" name="mail" id="form__mail" class="form__input mail">
</div>
</div>
<div class="form__group">
<div class="form-button__block">
<button type="button" name="submit" class="form__submit" id="form-submit">
<div class="arrow__btn-link-text">Let's Connect</div>
<amp-img src="stroke-arrow-right.svg" height="1" width="1"
alt="arrow right icon" class="arrow__btn-icon">
</button>
<!-- <div class="button--border"></div> -->
</div>
<div class="error_box">
<span class="error_message"></span>
</div>
</div>
</form>
JS:
var form = document.getElementById("form-submit"), msg;
form.addEventListener("click", function(event) {
event.preventDefault();
if (document.getElementById('form__textarea').value == '') {
msg = false;
} else {
msg = true;
}
if (document.getElementById('form__mail').value == '') {
email = false;
} else {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var validEmail = emailReg.test(document.getElementById('form__mail').value);
if (!validEmail) {
email = false;
} else {
email = true;
}
}
if (document.getElementById('form__phone').value == '') {
phone = true;
document.getElementById('form__phone').value = "";
} else {
var phoneReg = /^([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})/;
var validPhone = phoneReg.test(document.getElementById('form__phone').value);
if (!validPhone) {
phone = false;
} else {
phone = true;
}
}
if (document.getElementById('form__name').value == '') {
document.getElementById('form__name').value = "";
} else {
name = true;
}
if (!msg || !email || !phone) {
console.log("Error in formmmmmmmmmmmmm");
return false;
} else {
console.log("valid formmmmmmmmmmmmmmmmmmmmmm");
}
});

Doing a web site with validation form

I currently trying to make a website with a validating booking form for a university a project about a university portal. It used to work with my javascript validation until I added to validate time. Problem is sumbit button not working when I add to validate time and whenever I remove it is working.
HTML and JavaScript
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>
Any suggestions?
You should do this kind of thing with required.
<input type="email" required>
Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.
(https://www.w3schools.com/tags/att_input_required.asp)
There also exist pattern. For example, if you want to allow only six letters
<input type="text" pattern="[A-Za-z]{6}" required>
Here's a stackoverflow question that gives more information.
As i can see, the problem isn't on validateDate but on validateWorkshop. If you try to submit a blank form, without choosing a workshop, reason.length gets value 5. But if you pick a workshop, reason.length gets 13.
Not that i recomend your validation but to get this working, i just added a var error = ""; at the begining of validateWorkshop.
/** Validation Form**/
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateID(contact.id);
reason += validateWorkshop(contact.workshop);
reason += validateDate(contact.date);
console.log(reason);
if (reason.length > 0) {
return false;
} else {
return true;
}
}
/**Validate name**/
function validateName(name) {
var error = "";
if (name.value.length == 0) {
document.getElementById('name-error').innerHTML = "Please enter your First name.";
var error = "1";
} else {
document.getElementById('name-error').innerHTML = '';
}
return error;
}
/**Validate email as required field and format**/
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value);
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
document.getElementById('email-error').innerHTML = "Please enter your Email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { /**test email for illegal characters**/
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
document.getElementById('email-error').innerHTML = '';
}
return error;
}
/**Validate phone for required and format**/
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter your phone number";
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
} else {
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
/**Validate student ID**/
function validateID(id) {
var error = "";
if (id.value.length == 0) {
document.getElementById('id-error').innerHTML = "Please enter your ID.";
var error = "1";
} else {
document.getElementById('id-error').innerHTML = '';
}
return error;
}
/**Validate workshop select**/
function validateWorkshop(workshop) {
var error = "";
if ((contact.workshop[0].checked == false) && (contact.workshop[1].checked == false) && (contact.workshop[2].checked == false) && (contact.workshop[3].checked == false) && (contact.workshop[4].checked == false) && (contact.workshop[5].checked == false)) {
document.getElementById('workshop-error').innerHTML = "You must select a workshop";
var error = "2";
} else {
document.getElementById('workshop-error').innerHTML = '';
}
return error;
}
/**Validate date**/
function validateDate(date) {
var error = "";
if (date.value.length == 0) {
document.getElementById('date-error').innerHTML = "Please enter a date.";
var error = "1";
} else {
document.getElementById('date-error').innerHTML = '';
}
return error;
}
<header>
<center><img src="portal2.png" style="width:1000px;height:100px;"></center>
<p align="right">
<a href=".pdf" download>
<font color="darkblue">
<font size="5"><b>Report</font></b></a>
</p>
</header>
<hr class="line">
<div class="topnav" id="myTopnav">
Home
Timetable
Book a workshop
Contact
</div>
<br>
<br>
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="thankyou.html" method="post" target="_blank">
<div>
<label><u>First Name:</u></label><br>
<br>
<input type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<br>
<div>
<label><u>Email:</u></label><br>
<br>
<input type="email" name="email" id="email" tabindex="2" autofocus />
<div id="email-error" class="error"></div>
</div>
<br>
<div>
<label><u>Phone:</u></label><br>
<br>
<input type="tel" name="phone" id="phone" tabindex="3" autofocus />
<div id="phone-error" class="error"></div>
</div>
<br>
<div>
<label><u>Student ID:</u></label><br>
<br>
<input type="text" name="id" id="id" tabindex="4" autofocus />
<div id="id-error" class="error"></div>
</div>
<br>
<br>
<div>
<label><u>Please Select a workshop to book:</u></label>
<br>
<br>
<input type="radio" name="workshop" id="art" tabindex="5" autofocus />Art Workshop <br>
<input type="radio" name="workshop" id="computer" tabindex="6" autofocus />Computer Workshop <br>
<input type="radio" name="workshop" id="film" tabindex="7" autofocus />Film Production Workshop <br>
<input type="radio" name="workshop" id="music" tabindex="8" autofocus />Music Performance Workshop <br>
<input type="radio" name="workshop" id="journalism" tabindex="9" autofocus />Journalism Workshop <br>
<input type="radio" name="workshop" id="sociology" tabindex="10" autofocus />Sociology Workshop <br>
<div id="workshop-error" class="error"></div>
</div>
<br>
<p><u>Enter the date you want to book the workshop:</u></p>
<input type="date" name="date" id="date" min="2017-10-01" tabindex="11" autofocus />
<div id="date-error" class="error"></div>
<br>
<br>
<div>
<button type="submit" name="submit" id="submit" tabindex="12">Sumbit</button>
</div>
</form>
<br>
<br>
<footer>University. Copyright © 2015
<br>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Date();
</script>
<br>
</footer>

Categories