Want both PHP & JS form (empty fields/password match) validation? - javascript

I am designing an e-shop that allows profile registration. I need to have both Javascript & PHP validation for the registration form. (so when any of the fields are empty, I need to get a pop-up message that lets me know which specific field is empty + display on the screen beside the required field a visual message to advise the user where they need to correct the issue)
so far it is not working because my JS validation form activates onsubmit and my PHP is on action. I realize onsubmit activates before action and thus not allowing 'action' to go through.
I tried changing it from 'action' to 'onclick', but onsubmit also activates first and does not allow the PHP to work.
Here's my code for the form (I only included the first name portion so it won't get too long)
<form method="post" onclick="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="myForm" onsubmit="return validateForm()" style="border:1px solid #ccc">
<label><b>First Name</b></label>
<input type="text" name="firstName" placeholder="">
<?php echo $fnameErr;?>
<button type="submit" class="signupbtn" name="submit">Submit</button>
Here's my PHP code:
<?php
$fnameErr = "";
$fname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstName"])) {
$fnameErr = "Name is required";
}
else {
$fname = test_input($_POST["firstName"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I know the PHP code works, because if I delete the JS validation, it works as intended. I appreciate the help.
Please let me know if I need to add any extra information. Also, this hasn't been my first stop. I've been googling and trying to figure out how to fix this issue for hours to no avail...
This is the JS function being called (which also works as intended) this is also the shortened version to include only the name, the rest works the same, more if statements:
function validateForm() {
"use strict";
var fn = document.forms.myForm.firstName.value;
var ln = document.forms.myForm.lastName.value;
var em = document.forms.myForm.email.value;
var phone = document.forms.myForm.phone.value;
var pass = document.forms.myForm.psw.value;
var pass2 = document.forms.myForm.psw2.value;
if (fn === "") {
window.alert("First name must be filled out");
return false;
}
}

<input type="text" name="firstName" required>
You don't need any JavaScript.
Furthermore:
<form action="" method="post">
You don't need to specify the action if you're posting back to the current page. Using $_SERVER['PHP_SELF'] is potentially a vulnerability if you're not careful, and also breaks "pretty URLs" if you have them.

As said by #Niet The Dark Absol you can use the required but if you insist you can add e.preventdefault to prevent form from submitting in case of errors. We can elaborate properly if we can have a glimpse at your Javascript function.

You should change your onsubmit part and remove the onclick. Also your form is not valid as there is no action.
document.getElementById('myForm').addEventListener('submit',validateForm);
function validateForm(e) {
"use strict";
console.log(document.forms.myForm.firstName.value);
var fn = document.forms.myForm.firstName.value;
if (fn === "") {
window.alert("First name must be filled out");
e.preventDefault();
return false;
}
}
<form action="https://stackoverflow.com/" method="post" id="myForm">
<input type="text" name="firstName" >
<input type="submit">
</form>
There was a couple mistakes... But mainly what cause your problem is that onsubmit="return validateForm()". I also added e.preventDefault() it is to prevent the form submission if there is an error.

Related

How to submit a form as well as execute a javascript function in clicking an input button?

This code works, but it shows the heading only for an instant, How we can execute an sql query as well as javascript function to change the innerHTML on a form submission.
//HTML
<div id='heading'> </div>
//form
<form method='post'>
<input type='submit name='option' value='option' onclick='myFunction()' >
</form>
//sql query
if(isset($_POST['option'])===true && empty($_POST['option']===true)){
$sql2= 'SELECT * from maptable ORDER by price';
$result = $mysql->query($sql2);
}
//javascript function
<script>
function myFunction(){
document.getElementById('heading').innerHTML ='OptionName';
}
</script>
<input type='submit name='option'
Look at your code here. You skip a quote It should be like this <input type='submit' name='option'
As I see your form submitting without AJAX, so once you click "submit" button, the page will be reloaded and return a result of PHP script execution.
If you want to run your "myFunction" before submitting you can do this:
<form id="myForm">
...
</form>
<input type='button' name='option' onclick="myFunction()">
And "myFunction":
function myFunction(){
document.getElementById('heading').innerHTML ='OptionName';
document.getElementById('myForm').submit();
}
OR, if you want the "heading" div to be shown some time, you can submit the form using timeout:
function myFunction() {
document.getElementById('heading').innerHTML = 'OptionName';
setTimeout(function() {
document.getElementById('myForm').submit();
}, <timeout of submitting in milliseconds>);
}
If my understanding is correct, You want to call the function before the PHP code is executed.
Just change onclick="myFunction()" to onsubmit= "return myFunction()".
It's also a good practice to surrond your document.getElemen.... with a try catch block.
The way you are executing this at the moment isn't going to work. You are posting directly to the same page with your form without AJAX which means the page refreshes. Since JavaScript is client side, it's not going to persist your heading's innerHTML that you set. There are a million and one ways to fix this.
The quickest way to "fix" this is declare what you want the heading to be in your PHP processing and then output that in the H1 element if it exists:
#PHP
if(isset($_POST['option'])===true && empty($_POST['option']===true)){
$sql2= 'SELECT * from maptable ORDER by price';
$result = $mysql->query($sql2);
// Depending on what you want your Heading to be
// $headingName = $_POST['option'];
$headingName = "OptionName";
}
Set your HTML heading like so:
<div id='heading'><?php echo isset($headingName) ? $headingName : '' ?></div>
Also, your input is missing a quotation, and with this change, you don't need the JavaScript portion anymore:
<input type='submit' name='option' value='option'>

First form from many gets submitted on click

Problem: Multiple forms on the same page, but only the first one is being submitted.
Tried the following:
Equating the data-ids of submit button and Form inorder to submit the clicked form (No Luck)
Dynamic form creation using Javascript.(disbanded that idea after a few tries since it was on a deadline)
Usecase
The number of forms depends on the User. If there is just one comment from him, the form submits, while if there are say 4 forms, only the first one will submit.
Javascript:
$(function() {
$(".submit").click(function() {
var data_id = $(this).data('id');
var form_id = $(this.form).data('id');
if (parseInt(data_id, 10) == parseInt(form_id, 10)) {
var commentid = document.getElementByID('commentid');
alert(commentid + formid);
} else {
alert("10");
}
});
});
PHP code:
if($comment['Comment_Username'] ==$this->getUser()->getName())
{$output .='div class="panel" data-class="'.$comment['CommentID'].'">';
$output .='<form class="form" action="" method="post" data- id="'.$comment['CommentID'].'">';
$output .='<textarea name="edit_text' class="box" rows="2" cols="1">'.$this->getCommentText($comment['Comment_Text']).'</textarea>';
$output .='<input name="commentid" type="hidden" id="commentid" value="'.$comment['CommentID'].'"/>';
$output .='<input type="button' data-id="'.$comment['CommentID'].'" class="submit" value="submit"/>';
Any help would be greatly appreciated.
Thanks in advance
Wrong quote used here
$output .='<textarea name="edit_text" class="box" rows="2" cols="1">'.$this->getCommentText($comment['Comment_Text']).'</textarea>';

HTML Form using Javascript did not verify instead changed the link

Code:
<h1>Login Form</h1>
<form onsubmit="loginUsingPassword(this.form.loginPassword.value);return false;">
Password : <input type="password" name="loginPassword" /> <input type="submit" value="Submit" />
</form>
<script>
//This is for verifying use.
function generateUserPassword(){
var passwordArray = [];
passwordArray[0]="198237645";
passwordArray[1]="infotalkong";
function loginUsingPassword(inputPassword){
for (int i; i<passwordArray.length; i++){
if (inputPassword=passwordArray[i]){
document.cookie="reportLogged=true;";
window.location.href="http://tool-box.weebly.com/report.html";
}
}
}
</script>
Result:
Input : 198237645
Output : The link changed to http://tool-box.weebly.com/report-login.html?loginPassword=198237645
What is the solution?
I am not quite sure of your requirement, but there are some points might be helpful for you,
Generally we use method post for such form submission, rather than the default one(get).
So you might want to to change the follow code
<form onsubmit="loginUsingPassword(this.form.loginPassword.value);return false;">
to the follow one
<form onsubmit="loginUsingPassword(this.form.loginPassword.value);return false;" method="post">
After you do the above change, the password will not be displayed in the URL as you mentioned, to avoid security issue.
By reading your code, I assume you would like to check whether the password inputed by user is the same as a list of predefined password in your code.
But you have the follow code there
if (inputPassword=passwordArray[i]){//This is a common bug to mistake === to = in if
If you would like to compare the variable inputPassword and your predefined passwords(passwordArray), you should use == or === rather than the assignment operation(=), so the code should be
if (inputPassword === passwordArray[i]){
Hope the above hints could help you on debug your code.
Here is a working version based on my understanding to your requirement, but actually you didn't specify your requirement...
<h1>Login Form</h1>
<form onsubmit="loginUsingPassword(document.forms['myForm']['loginPassword'].value);return false;" method="post" name="myForm">
Password : <input type="password" name="loginPassword" /> <input type="submit" value="Submit" />
</form>
<script>
//This is for verifying use.
var passwordArray = [];
function generateUserPassword(){
passwordArray[0]="198237645";
passwordArray[1]="infotalkong";
}
function loginUsingPassword(inputPassword) {
generateUserPassword();
var passwordCorrect = false;
for (i = 0; i< passwordArray.length; i++){
if (inputPassword === passwordArray[i]){
document.cookie="reportLogged=true;";
passwordCorrect = true;
window.location.href="http://tool-box.weebly.com/report.html";
}
}
if (passwordCorrect !== true){
alert("Wrong Password!");
return false;
}
}
</script>
Your form tag has no method attribute, so it defaults to GET. It has no action attribute, so it defaults to the page you're on. If you submit the form, it encodes the submitted values in the URL (how GET is designed to work) and you land on the same page. This is exactly the behavior you have specified.

Submit form interfering with others

I have this email subscribe form for newsletter which gets delivered to me by email using PHP. It is located in footer which means that it is available on all pages across the website.
JSFIDDLE DEMO
Form works ok now but the problem is that it is interfering with other parts of website where forms are included - it messes those up and causes error to show on other fields as well.
My question is how do I isolate this form and script only for this part of the code so it will be defined only for this part of the webpage? What am I doing wrong?
As noted in the comments above,, you need to replace the "id" attributes in the html with "class" attributes. Then, modify your jQuery finders to search by class, constrained within the #subscribe form.
The HTML
<form id="subscribe" name="subscribe" action="#" method="post">
<input name="email" type="email" class="email" placeholder="Your e-mail adresss">
<span><button class="send" type="button">Subscribe</button></span>
</form>
And the Javascript
$(document).ready(function () {
$("#subscribe").submit(function () {
return false;
});
$("#subscribe .send").on("click", function () {
$('#subscribe input.error').removeClass('error');
var emailval = $("#subscribe .email").val();
var mailvalid = validateEmail(emailval);
if (mailvalid == false) {
$("#subscribe .email").addClass("error");
}
var minlen = $('#subscribe input[minlength]').filter(function(){
return this.value.length < +$(this).attr('minlength')
}).addClass('error').length;
if (mailvalid == true && minlen == 0) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<p><strong>Sending, please wait...</strong></p>");
$.ajax({
//you shouldn't need to change what you had here in the Fiddle; I didn't
//copy it for brevity's sake
});
}
});
});

Prevent action attribute from running php script with javascript [duplicate]

This question already has answers here:
prevent form from POSTing until javascript code is satisfied
(4 answers)
Closed 9 years ago.
Is there a way that I can use javascript to prevent a form from runing a php script. For example something like this:
<form action="somePage.php" method="POST>
<input type= "text" class= "field" name = "blah">
<input type="submit" value="Send" >
</form>
I know how to validate what's in that text box using javascript, but I want to prevent the somePage.php to run if the text box is empty. I haven't really tried anything cause I just don't know how to do it.
Hope you guys understand my problem.
Thanks
You can attach function to submit event of the form:
document.getElementById('form-id').addEventListener("submit", function(e){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null){
e.preventDefault();
alert('Pls fill the required fields.');
return;
}
return true;
});
OR
Below solution uses inline js:
If you want to run your js function before submitting the form to php script, you can use onsubmit attribute of the form,
<form id="form-id" action="somePage.php" method="POST" onsubmit="return formSubmit();">
<input type= "text" class= "field" id="field1" name = "blah">
<input type="submit" value="Send" >
</form>
In formSubmit function you can check the value of the input, if its empty or not, and if empty, then you can just return false;
var formSubmit = function(){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null)
return false;
else
return true;
}
You simply need to return false for your submit event by grabbing the form (I used querySelector because you have no IDs or classes), and adding a submit listening event to return false.
var x = document.querySelector("[method='POST']");
x.addEventListener("submit",function() {
return false;
});
Use this code to prevent form from submitting:
var first_form = document.getElementsByTagName('form')[0];
first_form.addEventListener('submit', function (e) {
e.preventDefault(); //This actually prevent browser default behaviour
alert('Don\'t submit');
//Do your stuff here
}, false);
Better read docs
you could in your somePage.php have this be a clause somewhere new the beggin:
if(empty($_POST['blah'])){
die();
}
or the inverse of
if(!empty($_POST['blah'])){
//do what this php is supposed to
}
else{
//display error
}
this will prevent your php from running if that field is not filled out.
Personally I return them to the same page setting some error on the page.

Categories