PHP/JavaScript form validation, invalid email check - javascript

So i'm working on form validation for a website.
What i have accomplished so far is when the form is submitted, validate.php checks if the email is in the correct format.
If it is, it proceeds in calling the sendMail() function included in the validate.php which proceeds in sending the email and then redirects the user back to the home page after 5 seconds. (This part works <-)
If it isn't, that's where i'm stuck.
What i'm trying to accomplish at this stage, is somehow get PHP to send a script tag, <script> emailError(); </script>, to the current page (contact.html) and execute the script which simply appends a paragraph saying that the email is incorrect. What i am getting, however is the validate.php has its own error in the else statement simply saying Error in a blank page (which is what i don't want, i put it there to see if the validation was working correctly).
I tried to add this (the script mentioned above) in the else statement in validate.php:
validate.php
<?php
include "mail.php";
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
sendMail();
}else {
echo("<script> emailError(); </script>");
}
?>
So what i was hoping it would do, is echo it into the page executing the JavaScript function but it didn't work and i think i know why.
PHP, to my knowledge, executes on request of user interaction (press button, click something, etc...) or upon page loading (Correct me if i'm wrong, still learning).
To make sure that the echo did not work, i inspected the page in real-time while using the form and didn't see any sign of the script tag being inserted into the HTML.
At this point, i have tried many alternative solutions, i don't even know where to begin. I could really use some help and any tips for improving my form.
This is the contact page that i'm working on. Feel free to try it out and see the results for yourself but Please don't spam!
Click Here
emailError.js
This is what i wanted to echo into the page with PHP.
function emailError(){
var targetElement = document.getElementById("emailform");
var errorElement = document.createElement("P");
var errorMessage = document.createTextNode("Invalid Email");
errorElement.appendChild(errorMessage);
errorElement.setAttribute("id","error");
document.body.appendChild(errorElement);
}
contact.html
This is just a segment of contact.html showing my form.
<form action="validate.php" method="post" id="emailform">
<required>* - Required</required><br>
<name>Name:* <input type="text" name="name" id="name" required /></name><br>
<email>Email:* <input type="text" name="email" id="email" required /></email> <br>
<message>Message:*<br><textarea rows="5" name="message" id="message" maxlength="1000" required></textarea></message><br>
<submit><input type="submit" value="Send" name="send" id="send" /></submit>
</form>
I'm not asking for something to copy n' paste, simply something to push me in the right direction.

Well, first of all, You are submitting your form to validate.php, and then never redirect back to contact.html, that's why you dont see the script tag appended. And from whay i see, that string 'Error' does not appear to be in your code, so I'm guessing that you did not paste the entire code. My suggestion, is to redirect to the contact form back again if the condition fails, and change contact.html to contact.php in order to be able to do a validation. Here is some rough code:
<?php
include "mail.php";
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
sendMail();
}else {
header('Location: contact.php?error=1');
}
?>
and then, in your contact.php file:
<form action="validate.php" method="post" id="emailform">
<required>* - Required</required><br>
<name>Name:* <input type="text" name="name" id="name" required /></name><br>
<email>Email:* <input type="text" name="email" id="email" required /></email> <br>
<message>Message:*<br><textarea rows="5" name="message" id="message" maxlength="1000" required></textarea></message><br>
<submit><input type="submit" value="Send" name="send" id="send" /></submit>
</form>
if ($_GET['error']) {
echo "<script> emailError(); </script>";
}
This is just a rough example, it can be more robust, with this solution, if somebody enters your contact form with the query param "error" he will get the javascript executed. But as I said, this is a concept and a rough solution to explain how you could solve your problem.

You can't execute java function like you are trying to.
If you use ajax, than in the success response function, set the respone to a div.
For example, if you have a success function that gets the data in an argument called data, than set an empty div with an ID like "emailResponse" in your page, and use this in the function:
var responseDiv = document.getElementById("emailResponse");
responseDiv.innerHtml = data;
Add this to your html:
<form action="validate.php" method="post" id="emailform">
<required>* - Required</required><br>
<name>Name:* <input type="text" name="name" id="name" required /></name><br>
<email>Email:* <input type="text" name="email" id="email" required /></email> <br>
<message>Message:*<br><textarea rows="5" name="message" id="message" maxlength="1000" required></textarea></message><br>
<submit><input type="submit" value="Send" name="send" id="send" /></submit>
<div id="emailResponse"></div>
</form>
And in your PHP, change to this:
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
sendMail();
echo "Your message was sent!";
}else {
echo "You email was invalid!";
}
UPDATE:
If you are not using ajax - you need to redirect to the contact page with some parameter in GET, or set some SESSION variable.

Related

Taking data from 1 website(input) and pasting it to another website(input)

I need to take a data of username, then check in db, which aunthefecator user has got and depends on aunthefecator send him the window where he can enter it and login in his account!
I have tryed to make it like a 1 form and the method was sent to another form but it doesn not work.
<form name="logon" action="check_login.php" method="POST" id="login">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">
<span>Log IN</span>
</button>
</form>
I just redirecting on this page without getting data.
You must put this code in top of your php page, or if you want to check login in another page , you should put this code in destination page that you want to check login authentication. Remember to put your code about checking user and pass from database.
<?php
if(isset($_POST[“username”] && $_POST[“password”]){
$user = $_POST[“username”];
$pass = $_POST[“password”];
//Check your db here and then replace your url that you want to reload client if user and pass was correct.
header(‘Location: http://yourURL.com’);
}else{
echo (“username or password was not correct”);
}
?>

How to autopopulate a text box in html and php

So I have a page where a new user can input a username pswrd ect. then they fill out some information. An admin can then go and see whos registered and If so desired can go and edit the information entered by the user. What happens is when the admin clicks a button that redirects them to the schedule page I want the text fields to already be populated with all the information. I have confirmed with echo statements that I do have all the correct information at button press, I just cant get the text fields to update when the page loads.
Here is an example of one of the text boxes
<input type="text" id = "textBoxSchedule" name="email" placeholder="Email" value="<?php echo $email?>" required>
I have correctly set the value of $email, but what my guess is, is that HTML runs, creates the text box and then the PHP runs so its set after the value is created.
Thank you for your help!
EDIT:
Ok so heres how I get the information. From the admin page, I know what user I want to edit. So I pass that user name value through the $_SESSION variable and then I can use that one piece of information to get the rest of the text fields. Im not sure if this will have an affect or if its something I can utalize but the text boxes are below a header of:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method = "post">
(im partner coding this and he wrote a majority of this so im still working on understanding it all.)
Try using javascript for it.
<input type="text" id = "textBoxSchedule" name="email" placeholder="Email" required>
<?php echo "<script>myFunction(".$email."); </script>" ?>
The JS is ~
myFunction(x){
document.getElementById('textBoxSchedule').value = x;
}
Don't have enough reputation to comment, so I'll post an answer
<?php echo $email?>
You forgot the semicolon ( ; ) and you didn't leave a space before ?>
Also although it's not false, you should not put spaces before and after = symbol in html attributes
id = "textBoxSchedule"
Lastly I presume you reload the page and you don't expect php to run in client's browser?
I’ve tested your script on a blank php page with the following code:
<?php
$email = "test#email.com";
?>
<input type="text" id = "textBoxSchedule" name="email" placeholder="Email" value="<?php echo $email?>" required>
And I’ve managed to get the text box showing properly.
If you still have a problem showing your text box, you might want to double check the value of your $email variable of the code prior and after the example you’ve given us.

jQuery/PHP ajax contact form

I have been fighting with this for quite awhile, searching questions, tutorials, and forums to not find a working solution. I'm extremely green in the realm of PHP and just now starting to learn.
Page in progress can be found here: http://williamsfuller.com/limedropdesign/
Goal: Use front end validation using jQuery Validate (http://jqueryvalidation.org/), if validation is successful then in the submitHandler run an ajax call to a php file that takes the form values and posts them to the server. On the ajax.done function clear the form and show that the submission has been successful.
Reason I'm using ajax is because I don't want the page to refresh and send the user back to the top of the page. This is a single page portfolio and if I was to do a post method on the form it will ruin the experience by reloading the page.
What I have achieved thus far:
-I have the jQuery validation working
-If the validation is successful the ajax call runs correctly activating the contact form submission file
-On the ajax.done function the contact form clears and a success message slides down telling the user the message has been sent
-On the php side of things I was able to hardcode a mail function that runs which tells me that the ajax call is working and the php file is working.
<?php
mail('email#gmail.com', 'Mail from Lime Drop Design', 'some body content for the email ');
?>
Where I'm stuck is taking the jQuery values and putting them into a working if($_POST){} and having that send off an email.
I also have a honey pot in the form to catch some bots, if all the information is validated and the subject field is still filled out I'm looking to just allow the POST to die.
HTML:
<form id="contactForm" method="get" action="">
<div class="form-group">
<input class="form-control"
type="text"
name="name"
id="name"
minlength="2"
placeholder="Name" required>
</div>
<div class="form-group">
<input class="form-control"
type="email"
name="email"
id="email"
placeholder="Your email address" required>
</div>
<div class="form-group">
<textarea class="form-control contactMessage"
name="message"
id="message"
rows="8"
minlength="10"
placeholder="Enter a message" required></textarea>
</div>
<input type="text" id="subject" name="subject" autocomplete="off">
<div class="form-actions">
<input type="hidden" name="save" value="contact">
<button id="formSubmit" type="submit" class="btn contact-btn pull-right">Send</button>
</div>
<div id="result">
Thank you, your message has been sent to Liz!
</div>
</form>
JavaScript:
$(document).ready(function(){
$('#result').hide();
$.validator.setDefaults({
submitHandler: function() {
var nameValue = $('#name').val();
var emailValue = $('#email').val();
var messageValue = $('#message').val();
console.log(nameValue, emailValue, messageValue);
$.ajax({
type: "GET",
url: "contactSubmission.php",
data: {
name: $('#name').val(),
email: $('#email').val(),
message: $('#messageValue').val()
}
}).done(function(){
$('#contactForm').find("input[type=text], input[type=email], textarea").val("");
$('#result').slideDown();
});
}
});
$("#contactForm").validate();
)};
PHP Working:
<?php
mail('email#gmail.com', 'Mail from Lime Drop Design', 'some body content for the email outisde post function');
?>
PHP not working (what I'm trying to achieve):
<?php
if($_POST){
$to = 'email#gmail.com';
$subject = 'Contact Form Submission';
$message = $_POST['messageValue'];
if($_POST['subject'] != ''){
die();
}
//Sanitize input data using PHP filter_var().
$nameValue = filter_var($_POST["nameValue"], FILTER_SANITIZE_STRING);
$emailValue = filter_var($_POST["emailValue"], FILTER_SANITIZE_EMAIL);
$messageValue = filter_var($_POST["messageValue"], FILTER_SANITIZE_STRING);
mail($to, $subject, $message);
}
?>
Any help on this would be greatly appreciated. I have been trying to get this to work for awhile now and I seem to just be stuck on the php POST at this point. Thanks in advance for any input or working example.
As pointed out, you're making a GET request with Jquery while php expect a POST one.
Then on your php, the post fields aren't good: You put 'Value' post field:
$_POST["nameValue"] while on Jquery it seems like the field is named name, try changing $_POST["nameValue"] to $_POST["name"] And do the same for message and email.
EDIT : Change $('#messageValue').val() to $('#message').val() in the post datas in your Jquery code, this value was the reason why the data wasn't succefully sent to PHP, in you console.log you've put the right ID but not in the post data, that's why you where thinking the correct values was sent by php.

Variable Transfer: Web Form that connects with PHP to Database

Hello and thank you for viewing my question. I am a complete beginner and am looking for simple ways to do the following...
What I have in seperate linked documents:
HTML, CSS, Javascript, PHP
What I am having trouble with:
I need to use something like JSON (although I would also accept XML requests or Ajax at this point if they work) to transfer variables from Javascript to PHP. I need the variables to search in a database, so they need to be literally available within PHP (not only seen on a pop-up message or something).
I have seen a LOT of different ways to do this, I have even watched tutorials on YouTube, but nothing has worked for me yet. The things I am having the biggest problem with is that when I add a submit button to my form it doesn't submit my form and I don't know why.
Form code snippet:
<form id="form" name="input" method="post" action="javascript:proofLength();">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit" onsubmit="post();">
</form>
The second to last line there doesn't work. Do I need javascript to submit the form? Because I really thought that in this case it was part of the functionality of the form just like method="post"...
The other thing is that for JSON, I have no idea what to do because my variables are determined by user input. Therefore, I cannot define them myself. They are only defined by document.getElement... and that doesn't fit the syntax of JSON.
Those are really my main problems at the moment. So if anyone could show me a simple way to get this variable transfer done, that would be amazing.
After this I will need to search/compare in my database with some php/sql (it's already connecting fine), and I need to be able to return information back to a in HTML based on what I find to be true. I saw one example, but I am not sure that was very applicable to what I am doing, so if you are able to explain how to do that, that would be great also.
Thank you very, very much.
April
You don't need ajax to submit this form. You don't even need javscript. Just do this:
<form id="form" name="input" method="post" action="mytarget.php">
<input id="userinput" name="userinput" type="text" autofocus />
<input id="submit" type="submit" value="submit" />
</form>
This will send the form data to mytarget.php (can be changed of course)
See that i have added the name attribute to your text-field in the form and i changed the type of the button to submit.
Now you can work the Data in mytarget.php like this:
<?
$username = $_POST['userinput'];
echo "Your name is: ".$username;
?>
You wanted to have a check for length in the submit. There are two ways to this:
Before the input is send (the server is not bothered)
Let the server Check the input
for 1 you will have to append a event listener, like this:
var form = document.getElementById("form");
form.addEventListener("submit", function(event){
console.log("test");
var name = form.elements['userinput'].value;
if(name.length < 3){
alert("boy your name is short!");
event.preventDefault();
}
});
Enter a name with less then 3 characters and the form will not be submitted. test here: http://jsfiddle.net/NicoO/c47cr/
Test it Serverside
In your mytarget.php:
<?
$username = $_POST['userinput'];
if(strlen($username) > 3)
echo "Your name is: ".$username;
else
echo "your name was too short!";
?>
You may also do all this with ajax. You will find a lot of good content here. But I'd recommend a framework like jQuery to do so.
The problem is in this line
<form id="form" name="input" method="post" action="javascript:proofLength();">
The action should be a PHP page (or any other type of server script) that will process the form.
Or the proofLength function must call submit() on the form
In the php page you can obtain variable values using $_GET["name"] or $_POST["name"]
To summarize; your code should look like this
<form id="form" name="input" method="post" action="yourpage.php">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit">
</form>
and for your php page:
<?php
$userinput = $_POST["userinput"];
//Do what ever you need here
?>
If you want to do something in your javascript before submitting the form, refer to this answer

error: "Please use POST request" with Form and Javascript

I made a small form and I want it to post information back to the user when the inputs are left blank.
For some reason it says please use post request, so I added it and now it gives me a different error message.
Here is the code:
http://jsfiddle.net/pwtnY/
<div id="main">
<form name="myForm" method="post">
<label><span>First Name:</span><input type="text" class="firstname" name="fname"></label><br/>
<label><span>Last Name:</span><input type="text" class="lastname"></label><br>
<label><span>E-Mail:</span><input type="text" class="email"></label><br/>
<label><span>Phone:</span><input type="text" class="phone"></label><br/>
<input type="submit" name="submit">
</form>
<div id="answer"></div>
</div>
Javascript:
$(document).ready(function(){
$('input:submit').click(function(){
$firstname = $('.firstname').val();
$lastname = $('.lastname').val();
$email = $('.email').val();
$phone = $('.phone').val();
if($firstname === "" && $lastname==="" && $email ==="" && $phone === ""){
$("#answer").html("Please fill out all fields.");
}
});
});
Anyone know what the problem could be and how I could go about solving it?
When you click submit, the form is actually posting to your django backend. If you want to do frontend validation before posting to your server, prevent the submit button from actually posting.
$('input:submit').click(function(event){
event.preventDefault();
$firstname = $('.firstname').val();
In your fiddle you haven't included jquery library. If you don't want to submit anything to the server, replace submit button with simple button <input type="button" value="submit">. There is updated your example: fiddle
P.S. You probably want to use OR instead of AND in your validation to validate if any of the fields is empty

Categories

Resources