Hey I have some trouble with my email subscription I'm trying to log into a textfile.
<!-- Signup Form -->
<form id="signup-form" action="form.php" method="post">
<input type="email" name="email" id="email" placeholder="Email Address" />
<input type="submit" value="Sign Up" />
</form>
Here's my PHP code:
<?php
if(empty($_POST['submit']) === false) {
$email = htmlentities(strip_tags($_POST['email']));
$logname = 'email.txt';
$logcontents = file_get_contents($logname);
if(strpos($logcontents,$email)) {
die('You are already subscribed.');
} else {
$filecontents = $email.',';
$fileopen = fopen($logname,'a+');
$filewrite = fwrite($fopen,$filecontents);
$fileclose = fclose($fileopen);
if(!$fileopen or !$filewrite or !$fileclose) {
die('Error occured');
} else {
echo 'Your email has been added.';
}
}
}
?>
I keep getting Cannot POST /form.php eventho the php file is at that path, someone knows what I'm possibly doing wrong? I'm quit noob at this :(
First of all add name attribute to your submit button, as in POST you will not get the form value of "submit" and your code will never go further
<form id="signup-form" action="form.php" method="post">
<input type="email" name="email" id="email" placeholder="Email Address" />
<input type="submit" name="submit" value="Sign Up" />
</form>
Now in your php code, you just need to check $_POST['submit'] in if condition and you have also done a typo, you have used a variable $fopen which is not defined, change that.
<?php
if($_POST['submit']) {
$email = htmlentities(strip_tags($_POST['email']));
$logname = 'email.txt';
$logcontents = file_get_contents($logname);
if(strpos($logcontents,$email)) {
die('You are already subscribed.');
} else {
$filecontents = $email.',';
$fileopen = fopen($logname,'a+');
$filewrite = fwrite($fileopen,$filecontents);
$fileclose = fclose($fileopen);
if(!$fileopen or !$filewrite or !$fileclose) {
die('Error occured');
} else {
echo 'Your email has been added.';
}
}
}
?>
Related
I'm working on a signup form in PHP. The form is a div which opens when you click on a button. Here's my code:
if(!$fieldsFilled){
$unfilledFormsError = '<br><font class="text-error" id="unfilled-forms-error">One of more of the fields are empty.</font><br>';
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
console.log('test passed');
});
</script>";
}
This all executes after my form is submitted:
if (isset($_POST['signUp']))
Full PHP code:
<?php require 'dbconnect.php'; ?>
<?php
//Error message variable declarations
$unmatchedPasswordsError = "";
$unfilledFormsError = "";
$emailError = "";
//If sign up submit POST recieved
if (isset($_POST['signUp']))
{
//Start session
session_start();
$email = $connection->real_escape_string($_POST['suEmail']);
$result = mysqli_query($connection, "SELECT * FROM users WHERE email='".$email."'");
if ($result->num_rows)
{
$emailInUse = true;
}
else
{
$emailInUse = false;
}
//Search for empty fields
$required = array('suFirstName', 'suLastName', 'suEmail', 'suPassword', 'suVerifyPassword', 'suDisplayName');
$fieldsFilled = true;
foreach($required as $field)
{
if (empty($_POST[$field]))
{
$fieldsFilled = false;
}
else
{
$fieldsFilled = true;
}
}
if ($emailInUse)
{
$emailError = "The email is already in use.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
if(!$fieldsFilled)
{
$unfilledFormsError = '<br><font class="text-error" id="unfilled-forms-error">One of more of the fields are empty.</font><br>';
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
console.log('test passed');
});
</script>";
}
else
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailError = "The email is not valid.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
//Check for unverified password
if ($_POST['suPassword']!= $_POST['suConfirmPassword'])
{
$unmatchedPasswordsError = "The passwords do not match.";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('#home-sign-up-box').show();
});
</script>";
}
else
{
//Variable declaration for sign up POST values
$suFirstName = $_POST['suFirstName'];
$suLastName = $_POST['suLastName'];
$suEmail = $_POST['suEmail'];
$suPassword = $_POST['suPassword'];
$suDisplayName = $_POST['suDisplayName'];
//Insert POST values into database
$sql = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
//Redirect to 'email sent' webpage
header('Location: emailSent.php');
}
}
}
}
}
//If log in submit POST recieved
if (isset($_POST['logIn']))
{
//Variable declaration for log in POST values
$liEmail = $_POST['liEmail'];
$liPassword = $_POST['liPassword'];
//Search for log in credentials in dabase
$result = $connection->query("select * from users where email = '$liEmail' AND password = '$liPassword'");
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
//TODO: CHECK FOR REMEMBER ME CHECK
session_start();
$_SESSION['userID'] = $row['userID'];
}?>
HTML sign up div/form code:
<!-- Sign Up Box -->
<div class="sign-up-box" id="home-sign-up-box">
<img src="images/icons/x-close.png" class="x-close" id="home-sign-up-close" src="x-close">
<font class="subheader-bold font-raleway" id="box-sign-up-text">Sign Up</font>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input" value="<?php if(isset($_POST['suFirstName'])){echo $_POST['suFirstName'];}?>">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input" value="<?php if(isset($_POST['suLastName'])){echo $_POST['suLastName'];}?>">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input"value="<?php if(isset($_POST['suEmail'])){echo $_POST['suEmail'];}?>">
<?php
echo '<br><font class="text-error" id="email-error">',$emailError,'</font>';
?>
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<?php
echo '<br><font class="text-error" id="passwords-unmatched-error">',$unmatchedPasswordsError,'</font>';
?>
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input" value="<?php if(isset($_POST['suDisplayName'])){echo $_POST['suDisplayName'];}?>">
<?php
echo $unfilledFormsError;
?>
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<font class="text-minor" id="agree-tos-pp-text">By signing up, you agree to our terms of service and <br>privacy policy.</font>
</div>
The "test passed" does log to the console, however the div is not showing after the page refresh (due to form submission). Any help is appreciated! Thank you so much!
I have customized as your requirement and database connection i have used
Mysqli replace whatever you want also change database credentials.
Full code will be in same page. Try and comment if you don't understand anything.
<?php
session_start();
//require 'dbconnect.php';
$connection=mysqli_connect("localhost","root","","test"); // I have use it for testing
$errors = array();
if (isset($_POST['signUp'])) {
$email = mysqli_real_escape_string($connection, $_POST['suEmail']);
$result = mysqli_query($connection, "SELECT * FROM users WHERE email='".$email."'");
//email check
if(mysqli_num_rows($result)>0){
$errors[] = "The email is already in use.";
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors[] = "The email is not valid.";
}
//Search for empty fields
$required = array('suFirstName', 'suLastName', 'suEmail', 'suPassword', 'suConfirmPassword', 'suDisplayName');
foreach($required as $field){
if (empty($_POST[$field])){
$errors[] = $field." Cannot be empty.";
}
}
if(count($errors)==0){
if($_POST['suPassword']!=$_POST['suConfirmPassword']){
$errors[] = "The passwords do not match.";
}else{
$suFirstName = $_POST['suFirstName'];
$suLastName = $_POST['suLastName'];
$suEmail = $_POST['suEmail'];
$suPassword = $_POST['suPassword'];
$suDisplayName = $_POST['suDisplayName'];
//$sql = $connection->query("INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
$sql = mysqli_query($connection, "INSERT INTO users (firstName,lastName,email,password,displayName)Values('{$suFirstName}','{$suLastName}','{$suEmail}','{$suPassword}','{$suDisplayName}')");
if($sql){
header('Location: emailSent.php');
}else{
$errors[] = "Failed to insert.";
}
}
}
}
if (isset($_POST['logIn'])){
$liEmail = $_POST['liEmail'];
$liPassword = $_POST['liPassword'];
//$result = $connection->query("select * from users where email = '$liEmail' AND password = '$liPassword'");
$result = mysqli_query($connection, "select * from users where email = '$liEmail' AND password = '$liPassword'");
if($result){
$row = mysqli_fetch_assoc($result);
$_SESSION['userID'] = $row['userID'];
}
}
?>
<?php
if(!empty($errors)){
foreach ($errors as $value) {
echo "<span style='color:red;'>".$value."</span><br>";
}
}
?>
<button type="button" id="showSignup">Show Sign-up</button><br><br>
<!-- Sign Up Box -->
<div class="sign-up-box" id="home-sign-up-box">
<img src="images/icons/x-close.png" class="x-close" id="home-sign-up-close" src="x-close">
<font class="subheader-bold font-raleway" id="box-sign-up-text">Sign Up</font>
<form method="post" action="" id="home-sign-up-form">
<input type="text" name="suFirstName" placeholder="First Name" class="text-input-minor" id="sign-up-first-name-text-input" value="<?php if(isset($_POST['suFirstName'])){echo $_POST['suFirstName'];}?>">
<input type="text" name="suLastName" placeholder="Last Name" class="text-input-minor" id="sign-up-last-name-text-input" value="<?php if(isset($_POST['suLastName'])){echo $_POST['suLastName'];}?>">
<input type="text" name="suEmail" placeholder="Email" class="text-input-minor" id="sign-up-email-text-input"value="<?php if(isset($_POST['suEmail'])){echo $_POST['suEmail'];}?>">
<input type="password" name="suPassword" placeholder="Password" class="text-input-minor" id="sign-up-password-text-input">
<input type="password" name="suConfirmPassword" placeholder="Confirm Password" class="text-input-minor" id="sign-up-confirm-password-text-input">
<input type="text" name="suDisplayName" placeholder="Display Name (you can change this later)" class="text-input-minor" id="sign-up-display-name-text-input" value="<?php if(isset($_POST['suDisplayName'])){echo $_POST['suDisplayName'];}?>">
<label><input type="checkbox" name="suRememberMe" value="yes" id="sign-up-remember-me-checkbox"><font id="sign-up-remember-me-text">Remember me</font></label>
<input name="signUp" type="submit" value="Sign Up" id="sign-up-submit">
</form>
<font class="text-minor" id="agree-tos-pp-text">By signing up, you agree to our terms of service and <br>privacy policy.</font>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
<?php if(isset($_POST['signUp']) && count($errors)>0){ ?>
$('#home-sign-up-box').show();
<?php }elseif(isset($_POST['signUp']) && count($errors)==0){ ?>
//$('#home-sign-up-box').hide();
<?php }else{?>
//$('#home-sign-up-box').show();
<?php }?>
$("#showSignup").click(function(){
$('#home-sign-up-box').toggle();
visible_check();
});
visible_check();
});
function visible_check(){
var isVisible = $( "#home-sign-up-box" ).is( ":visible" );
if(isVisible){
$("#showSignup").html("Hide Sign-up");
}else{
$("#showSignup").html("Show Sign-up");
}
}
</script>
I am a very beginner in php.I tried a form validation in php while validating my form.when wrong data is found the browser will show an alert box, when i click it the browser reloads the page and the details already entered in the form get refreshed and i need to enter it from the first.
How to avoid the page refresh while validating.
sorry for my poor english
Thank you in advance
This is my php form coding
formvalidate.php
<html>
<head>
<title>USER REGISTRATION</title>
</head>
<body>
<form name="registrationform" id="formid" method="get";>
name:<input type="text" id="n1" name="name"> <br><br>
username:<input type="text" id="u1" name="username"> <br><br>
password:<input type="password" id="p1" name="password"> <br><br>
confirm password:<input type="password" id="p2" name="password2"> <br><br>
Address :<textarea name="address" id= "a1"rows="4" cols="40"> </textarea><br><br>
phone :<input id="ph" type="numbers" name="phone" ><br><br>
<input type="submit" name="register" value="register" >
<input id="button" type="button" value="cancel">
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="userlogin";
$conn=mysqli_connect($servername,$username,$password,$dbname);
if(!$conn)
{
die("connection failed".mysqli_connect_error());
}
?>
<?php
if (isset($_GET['register'])) {
if(empty($_GET['name']))
{
echo'name should not empty';
}
if ( empty($_GET['username'])) {
echo 'user name should not be empty';
} else {
$name1=$_GET['name'];
$uname=$_GET['username'];
$sql = "select * from contact where username='$uname'";
$result=mysqli_query($conn,$sql);
if($result->num_rows==1)
{
echo"username already exists";
}
else
{
echo"username available";
}
return false;
}
if((empty($_GET['password']))||(empty($_GET['confirmpassword'])))
{
echo'password and confirm password should not be empty';
return false;
}
else{
$pwd=$_GET['password'];
$cpwd=$_GET['confirmpassword'];
if($pwd.length==6){
echo'password should not lesser than 6';
}
else
{
if($pwd==$cpwd){
echo'password accepted';
}
else
{
echo 'password does not matched';
return false;
}
}
}
if(empty($_GET['address']))
{
echo'address should not be empty';
return false;
}
if(empty($_GET['phone']))
{
echo'phone should not be empty';
return false;
}
}
?>
</body>
</form>
</html>
You could perform the check at the start of page, something like;
$sParam1 = "";
if (isset ($_GET['param1']) ){
$sParam1 = (string)$_GET['param1'];
}
Leave the form at the bottom of the page and echo the variables in the value param;
<form method="get">
<input type="text" name="param1" value="<?php echo htmlspecialchars($sParam1); ?>" />
</form>
Yoy can also set something like
if(isset($_GET['name'] ){echo "value=$_GET[name]";}
for each of the input attributes.
Though i believe you should use POST attribute in form rather tham GET.
Also, you have not set the 'action' attribute for the form !
I am trying to implement a basic user registration RESTful api.
I have a html form registerform.html, deregisterform.html, users.php, register.php and deregister.php which are all pasted below.
When i visit the registerform.html in my browser, i can fill in the details and a POST request is received by the users.php script and a json response is echoed back showing the id number of the user thats just been added.
My problem is that when i use the deregister form, the users.php script should recive a DELETE request, but is actually getting a GET request. I've been looking for an answer to this problem but im not finding a solution.
registerform.html
<form action="users.php" method="POST">
Username: <input type="text" name="uname" /><br />
FirstName: <input type="text" name="fname" /><br />
Last Name: <input type="text" name="lname" /><br />
Date of Birth: <input type="date" name="dob" /><br />
Telephone: <input type="mob" name="tel" /><br />
Email: <input type="email" name="email1" /><br />
Confirm Email: <input type="email" name="email2" /><br />
Password: <input type="password" name="pass1" /><br />
Confirm Password: <input type="password" name ="pass2" /><br />
<input type="submit" value="Register" name="sub" />
<br/>Already Registered? Login Here<br/>
</form>
deregisterform.html
<form action="users.php" method="DELETE">
Username: <input type="text" name="uname" /><br />
Password: <input type="password" name="pass1" /><br />
Confirm Password: <input type="password" name ="pass2" /><br />
<input type="submit" value="Deregister" name="sub" />
</form>
register.php
<?php
if(isset($_POST['uname']) && isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['tel']) && isset($_POST['dob']) &&
isset($_POST['email1']) && isset($_POST['email2']) && isset($_POST['pass1']) && isset($_POST['pass2']))
{
//take values from http POST and trim whitespace
$uname = trim($_POST['uname']);
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$tel = trim($_POST['tel']);
$dob = trim($_POST['dob']);
$email1 = trim($_POST['email1']);
$email2 = trim($_POST['email2']);
$pass1 = trim($_POST['pass1']);
$pass2 = trim($_POST['pass2']);
//validate the data from the form
if($um->isNameFormatted($uname))
{
if(!$um->isUserExists($uname)) //does user already exist with this username?
{
if($um->isNameFormatted($fname)) //first name formatted correctly
{
if($um->isNameFormatted($lname)) //last name formatted correctly
{
if($um->isDOBFormatted($dob))
{
if($email1 == $email2)
{
if($pass1 == $pass2)
{
if($um->isPasswordClean($pass1))
{
if($um->isTelephoneVerified($tel))
{
//everything is OKAY --- PROCEED WITH ADDING USER
$user = $um->registerUser($uname,$fname,$lname,$dob,$tel,$email1,$pass1);
if(isset($user))///
{
//successful registration
$response["error"] = false;
$response["id"] = $user;
echo json_encode($response);
}
}
}
}
}
}
}
}
}
}
}?>
deregister.php
<?php
if(isset($_POST['uname']) && isset($_POST['pass1'] && isset($_POST['pass2'])
{
$uname = $_POST['uname'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($um->isUserExists($uname))
{
if($pass1 == $pass2)
{
if(true)//$um->isPasswordFor($uname, $pass))
{
$um->deregisterUser($uname, $pass1);
$response["error"] = false;
$response["text"] = "User removed!";
echo json_encode($response);
}
else
{
$response["error"] = true;
$response["text"] = "Wrong username and password combination!";
echo json_encode($response);
}
}
else
{
$response["error"] = true;
$response["text"] = "Passwords don't match!";
echo json_encode($response);
}
}
else
{
$response["error"] = true;
$response["text"] = "User(".$uname.") not in database!";
echo json_encode($response);
}
}?>
users.php
<?php
error_reporting( -1 );
require('userManagement.php');
$um = new UserManagement();
$response = array("error" => FALSE);
//check if user logged in and authenticated
if(true)
{
echo "user logged in.";
echo $httpVerb = trim(strtoupper($_SERVER['REQUEST_METHOD']));
switch($httpVerb)
{
case "GET":
$response["error"] = false;
$response["httpVerb"] = $httpVerb;
echo json_encode($response);
break;
case "PUT":
$response["error"] = false;
$response["httpVerb"] = $httpVerb;
echo json_encode($response);
break;
case "POST":
include('register.php');
break;
case "DELETE":
include('deregister.php');
break;
default:
echo "http verb ".$httpVerb." is not supported for this resource.";
$response["error"] = true;
$response["httpVerb"] = $httpVerb;
echo json_encode($response);
break;
}
}
else
{
echo "need to login first.";
}?>
Any ideas what i'm doing wrong?
You can't use DELETE as a form action.
From the specs, we have:
The method and formmethod content attributes are enumerated attributes
with the following keywords and states:
The keyword get, mapping to the state GET, indicating the HTTP GET method.
The keyword post, mapping to the state POST, indicating the HTTP POST method.
The invalid value default for these attributes is the GET state.
I have a form than when I submit incorrectly no error is displayed
<form action="emailSubs.php" method="post">
<p>Would you like to subscribe to our newsletter ?</p>
<p>Name: <input type="text" name="name"><br /></p>
<p>E-mail: <input type="text" name="Email"><br /></p>
<p><input type="submit" name="submit"><br /></p>
</form>
<?php
function validateEmail($data, $fieldName) {
global $errorCount;
if(empty($data)) {
echo "\"$fieldName\" is a required
field.<br />\n";
++$errorCount;
$retval = "";
} else { // olny clean up the input if it isn't
// empty
$retval = trim($data);
$retval = stripslashes($retval);
$pattern = "/^[\w-]+(\.[\w-]+)*#" .
"[\w-]+(\.[\w-]+)*" .
"(\[[a-z]]{2,})$/i";
if(preg_match($pattern, $retval) ==0) {
echo "\"$fieldName\" is not a valid E-mail
address.<br />\n";
++$errorCount;
}
}
return ($retval);
}
?>
I think it may be the pattern but am not sure what the problem may be
The problem is that you do not have the two things connected properly...
Leave your form in a separate file from emailSubs.php -
While this is not a necessary step, it will hopefully help you understand the way this works (not to mention it is a much neater / organized way to do it)
<form action="emailSubs.php" method="post">
<p>Would you like to subscribe to our newsletter ?</p>
<p>Name: <input type="text" name="name"><br /></p>
<p>E-mail: <input type="text" name="Email"><br /></p>
<p><input type="submit" name="submit"><br /></p>
</form>
Now, in your emailSubs.php file :
<?php
function validateEmail($data, $fieldName) {
global $errorCount;
if(empty($data)) {
echo "\"$fieldName\" is a required
field.<br />\n";
++$errorCount;
$retval = "";
} else { // olny clean up the input if it isn't
// empty
$retval = trim($data);
$retval = stripslashes($retval);
$pattern = "/^[\w-]+(\.[\w-]+)*#" .
"[\w-]+(\.[\w-]+)*" .
"(\[[a-z]]{2,})$/i";
if(preg_match($pattern, $retval) ==0) {
echo "\"$fieldName\" is not a valid E-mail
address.<br />\n";
++$errorCount;
}
}
return ($retval);
}
?>
But, you aren't done, yet -!
You see, you have to connect the two ---
In your form, you specified method="post" - so, we do this:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
?>
Now, there are plenty of good reasons to not use regexp to validate your form.
This is a good read on that topic.
So, what you might do instead, could look like this:
<?php
if(ctype_alnum($_POST['name']) == true){
$name = $_POST['name'];
} else {
exit("Please enter a valid name");
}
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL){
$email = $_POST['email'];
} else {
exit("Please enter a valid email address");
}
?>
And you see? That makes for a much cleaner way to handle your validation.
SO, Full circle, your code didn't display an error because there was nothing to display that error.
I noticed that you have a form, and a function but you don't call the function when the form is submitted. Maybe this is something you are doing outside the scope of the code you included, but just in case, I modified it to be a complete interaction between submission/function call and the form itself. Also, why not use filter_var instead of a regular expression?
Code (working on my local server):
<?php
function validateEmail($data, $fieldName)
{
global $errorCount;
$errorCount=0;
if(empty($data))
{
echo "\"$fieldName\" is a required
field.<br />\n";
++$errorCount;
$retval = "";
}
else
{
// olny clean up the input if it isn't
// empty
$retval = trim($data);
$retval = stripslashes($retval);
if(!filter_var($_POST['Email'], FILTER_VALIDATE_EMAIL))
{
echo "\"".$_POST['Email']."\" is not a valid E-mail
address.<br />\n";
++$errorCount;
}
}
return ($retval);
}
if(isset($_POST['submit']))
{
$email=validateEmail($_POST['Email'], "Email");
if(empty($errorCount))
{
//create subscription
echo "Subscribed!";
}
}
?>
<form action="test.php" method="post">
<p>Would you like to subscribe to our newsletter ?</p>
<p>Name: <input type="text" name="name" value="<?php echo $_POST['name'];?>"><br /></p>
<p>E-mail: <input type="text" name="Email" value="<?php echo $_POST['Email'];?>"><br /></p>
<p><input type="submit" name="submit"><br /></p>
</form>
I will be on the point. But anyways, THANKS IN ADVACE.
So basically When I submit the form I made, it submits and stuff, but it redirects the page to the PHP file, and shows this on the browser (not as an alert) :
{"status":"success","message":"Yer message was sent."}
when the data is successfully validated, and shows this
{"status":"fail","message":"Invalid name provided."}
when the form doesn't validate. What I want, is that when the form submits, it stays on the same page and if status is true or false, it should alert the message in the array.
I'll write down the scripts and the file names are: index.html, script.js and post.php
INDEX.HTML
<form action='post.php' id='post_message' name='post_message' method="post">
<p>
<input id='email' type="email" class='post' placeholder="Email goes in here.(Required) " class="width" name="email">
<br>
<input id='fname' type="text" class='post' placeholder="First Name (Required) " name="FirstName"><br>
<input id='lname' type="text" class='post' placeholder="Last Name (Required) " name="LastName"><br>
<input id='website' type="url" class='post' placeholder="Website? (Optional!)" class="width" name="website"><br>
<textarea id='message_text' placeholder="Your Message goes here. (Required, DUH!) " name='message'></textarea>
</p>
<button type="submit" class="submit" id='btnPost'></button>
<input type="hidden" name="action" value="post_message" id="action">
</form>
SCRIPT.JS
function clearInputs(){
$("#fname").val('');
$("#lname").val('');
$("#email").val('');
$("#website").val('');
$("#message_text").val('');
}
$('#btnPost').click(function() {
var data = $("#post_message").children().serializeArray();
$.post($("#post_message").attr('action'), data, function(json){
if (json.status == "fail") {
alert(json.message);
}
if (json.status == "success") {
alert(json.message);
clearInputs();
}
}, "json");
});
POST.PHP
<?php
if($_POST){
if ($_POST['action'] == 'post_message') {
$fname = htmlspecialchars($_POST['FirstName']);
$lname = htmlspecialchars($_POST['LastName']);
$email = htmlspecialchars($_POST['email']);
$website = htmlspecialchars($_POST['website']);
$message = htmlspecialchars($_POST['message']);
$date = date('F j, Y, g:i a');
if(preg_match('/[^\w\s]/i', $fname) || preg_match('/[^\w\s]/i', $lname)) {
fail('Invalid name provided.');
}
if( empty($fname) || empty($lname) ) {
fail('Please enter a first and last name.');
}
if( empty($message) ) {
fail('Please select a message.');
}
if( empty($email)) {
fail('Please enter an email');
}
$query = "INSERT INTO portmessage SET first_name='$fname', last_name='$lname', email = '$email', website = '$website', message = '$message', date = '$date'";
$result = db_connection($query);
if ($result) {
$msg = "Yer message was sent.";
success($msg);
} else {
fail('Message failed, Please try again.');
}
exit;
}
}
function db_connection($query) {
mysql_connect('127.0.0.1', '######', '####')
OR die(fail('Could not connect to database.'));
mysql_select_db('####');
return mysql_query($query);
}
function fail($message) {
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
?>
And yes, it DOES submit the form to the database, but I can't overcome the alert and redirecting problem.
Thanks, again!
You can validate your form client side(using javascript)
HTML
<form action='post.php' id='post_message' name='post_message' method="post" onsubmit="return validate_form();">
Javascript
function validate_form()
{
var success = true;
if($("[name=FirstName]").val() == "")
{
success = false;
}
// your test case goes here
// you can alert here if you find any error
return success;
}