I am having trouble inserting data into the database when my "submit" button is pressed from a form. I want to take the values inputted from the user and store those values in the table I created
<?php
if(isset($_POST['submit'])){
$email = $_POST['email'];
$link = $_POST['link'];
$email = $_POST['screenerAmount'];
$minutes = $_POST['minutes'];
$comments = $_POST['comments'];
//insert into table
$sql = "INSERT INTO test_myFilm (email, link, screeners, minutes, comments)
VALUES ('$email', '$link','$screenerAmount', '$minutes','$comments')";
if (mysqli_query($conn, $sql)) {
header('Location: submit_ThankYou.php' );
} else {
echo "Error: " . $sql . "
" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
Here is the form:
<div>
<form class="submit-film" action="testfilm.php" method="POST">
<p class="email">Email</p>
<input class="field" name="email" id="email" placeholder="youremail#example.com" required>
<p class="project_link">Link to your project:</p>
<input class="field" name="link" id="link" placeholder="https://vimeo.com/myfilm" required>
<p class="number">How many screeners do you want?</p>
<input class="field" name="screenerAmount" id="screenerAmount" placeholder="8 screeners" required>
<p class="please">Please attach a questionaire if you have one preparred:</p>
<input type="file" class="select">
<p class="length">How many minutes is your project?</p>
<input class="field" name="minutes" id="minutes" placeholder="15 minutes" required>
<p class="questions">Do you have any additional comments or questions?</p>
<input class="field" name="comments" id="comments" placeholder="(insert comments/questions here)">
<div>
<button type="submit" class="button_type" class="button_type:hover" value="Submit" name ='submit'>Submit</button>
</div>
</form>
</div>
My connection seems to be working and I am not receiving any error. I am using Javascript to validate the values inputted into the form fields, so I see the values logged to the console, but the page does not refresh when the "submit" button is pressed.
Javascript as requested:
const form = document.querySelector('.submit-film');
const emailPattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
const linkPattern = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/;
form.addEventListener('submit', e=> {
e.preventDefault();
//validation
const email = form.email.value;
if (emailPattern.test(email)){
true;
console.log(form.email.value);
} else if (email === ""){
alert("Please submit your email address so we can get in contact with you.")
false;
} else {
alert("You have entered an invalid email address!");
false;
}
const link = form.link.value;
if (linkPattern.test(link)){
true;
console.log(form.link.value);
} else if (link===""){
alert ("Please input a link to your project. If you do not have a link to your project simply input 'no link'");
false;
} else {
alert("Please input a valid URL for your film. Youtube, Google Drive, and Vimeo work great. If you are still having trouble email contact#entholigy.com for help.");
false;
}
const screenerAmount = form.screenerAmount.value;
if (screenerAmount==="" || screenerAmount.value === null){
alert("Please let us know how many screeners you want.");
} else {
console.log(form.screenerAmount.value);
}
// const foo = form.foo.value;
// console.log(foo);
const minutes = form.minutes.value;
if (minutes==="" || minutes.value === null){
alert("Please let us know how long your film is (in minutes)");
} else {
console.log(form.minutes.value);
}
console.log(form.comments.value);
});
const now = new(Date);
console.log(now);
Change your submit button to input as you're checking for $_POST['submit'] in your submit page. See if this works for you.
<input type="submit" class="button_type" value="submit" name='submit'>Submit</input>
Related
I made a website using css, html, javascript and a little php. I have it hosted on a hosting site with a domain name, but I'm having issue with the server side validation for the form.
It's just a simple contact form:
First Name
Last Name
Email
Message (textarea)
Submit button
I have javascript validation and it works fine. The form won't submit at all unless the correct amount of characters are input, but obviously that's useless if the user has js disabled. I've also finally gotten the form to email to my personal email using php... But obviously I need server side validation as well.
Today was my first day really getting into php and I was hoping to have the php validation done by today, but of all the videos I watched, I just came away more confused. All I want to do is just make it so that if the user has javascript disabled for whatever reason, or if he leaves the fields blank, the form won't submit...
Anyeay, I was working on this all day today with the intention of getting the form to send to my email, I finally accomplished that. Then realized I had no server side validation. I spent a few hours researching it and attempting it to no avail. Can anyone here just give me the php validation code for the kind of form I described above? It's for my business website so the sooner I can have a working contact form on it, the better...
Here is the html contact form I made.
<form action="message_sent.php" method="POST" onSubmit="return validateTextbox();">
<p class="message">
<div class="row">
<label for="firstname"><!--First Name (Required):--> </label>
<input type="text" id="firstname" name="first_name" size="40" placeholder="First Name (Required)"></br> </br> </div>
<div class="row">
<label for="lastname"><!--Last Name (Required):--> </label>
<input type="text" id="lastname" name="last_name" size="40" placeholder="Last Name (Required)"/> </br> </br></div>
<div class="row">
<label for="email"><!--Your Email (Required):--></label>
<input type="email" id="email" name="email" size="40" placeholder="Email (Required)"/> </br> </br></div>
<!--<p class="yourMessage">Your Message (10 Character Minimum):</p>-->
<textarea id="theform" rows="30" cols="80" name="message" placeholder="Your Message (10 Character Minimum):"></textarea></br>
</p>
<input type="submit" name="submit" onclick="return val();" value="SUBMIT">
</form>
</body>
</html>
Here is the javascript validation:
/*============================ CONTACT US PAGE ==========================*/
function validateTextbox() {
var box = document.getElementById("firstname");
var box2 = document.getElementById("lastname");
var box3 = document.getElementById("email");
var box4 = document.getElementById("theForm");
if (box.value.length < 1 || box2.value.length < 1 || box3.value.length < 5){
alert("You must enter a value");
box.focus();
box.style.border = "solid 3px red";
box2.focus();
box2.style.border = "solid 3px red";
box3.focus();
box3.style.border = "solid 3px red";
return false;
}
}
function val(){
if(document.getElementById("theform").value.length < 10
&& document.getElementById("theform").value.length > 0){
alert("You must enter at least 50 characters. Tell us what you need so we can better assist you.");
return false;
}
else if(document.getElementById("theform").value.length === 0){
alert("You cannot submit an empty form.");
theform.focus();
theform.style.border = "solid 3px red";
return false;
}
}
/*function val(){
if(document.getElementById("theform").value==null || document.getElementById("theform").value==""){
alert("The Message field cannot be blank.");
return false;
}
*/
/*
*/
/*=======================|| box4.value.length < 70) ================================================ */
/*========= CONTACT PAGE========================================*/
/*
function contactPage(){
alert("This Contact Form is NOT OPERATIONAL.");
Here is the php submission success page... the code I used to have the form send to my email:
<?php
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$email=$_POST['email'];
$message=$_POST['message'];
$to="default#email.com";
$subject="A visitor has sent you a new message";
$body="You have received a message from: \n\n
First Name: $first_name\n
Last Name: $last_name\n
Email: $email\n\n
MESSAGE: $message";
mail($to, $subject, $body);
print "<p>Message Sent! <a href='index.html'>Click. here</a> to return to the homepage</p>"
?>
Simple and complete example:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
//Define variable as empty to avoid "undefined variable error".
$FnameErr = $LnameErr = $emailErr = ""; //Each variable contain error string of specific field.
$fname = $lname = $email = $message = ""; //Main inputed data of specific field
if ($_SERVER["REQUEST_METHOD"] == "POST") { //check if request is posted.
//First name check
if (empty($_POST["fname"])) { // check if empty then assign a error string in spacific variable
$FnameErr = "First Name is required";
}else{ // if not empty then store as right data
$fname = filter_data($_POST["fname"]); //filter with unexpected special char and trim.
}
//Last name
if (empty($_POST["lname"])) { // check if empty then assign a error string in spacific variable
$LnameErr = "Last Name is required";
}else{ // if not empty then store as right data
$lname = filter_data($_POST["lname"]); //filter with unexpected special char and trim.
}
//email
if (empty($_POST["email"])) { // check if empty then assign a error string in spacific variable
$emailErr = "Email is required";
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // validate email with php build-in fucntion.
$emailErr = "Invalid email format";
}else{ // if not empty and valide email then store as right data
$email = filter_data($_POST["email"]); //filter with unexpected special char and trim.
}
}
//message with no validation
if (empty($_POST["message"])) {
$message = "";
} else {
$message = filter_data($_POST["message"]);
}
//Database query
if($FnameErr =="" && $LnameErr =="" && $emailErr==""){
//MYSQL insert statement that you know
// $sql = "INSERT INTO tablename .................."; values = $fname; $lname; $email; $message;
}
}
// A function to trim data and remove special charecter
function filter_data($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name: <input type="text" name="fname" value="">
<span class="error">* <?php echo $FnameErr;?></span><br><br>
Last Name: <input type="text" name="lname" value="">
<span class="error">* <?php echo $LnameErr;?></span><br><br>
E-mail: <input type="text" name="email" value="">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Message: <textarea name="message" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $fname;
echo "<br>";
echo $lname;
echo "<br>";
echo $email;
echo "<br>";
echo $message;
?>
</body>
</html>
This is just a basic empty check validation.
Validations in PHP are not very difficult.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(trim($_POST['firstname']) === ''){
echo 'Please enter firstname';
}
}
You can also learn some validations here
http://www.w3schools.com/php/php_form_validation.asp
I have two PHP pages: index.php and thankyou.php. In index.php, there is a form. I am validating form with Javascript and ajax and the form values are being inserted into database. After database query I am redirecting this form to Thankyou.php. What i want is to pass form field values to thankyou.php. Please find below the complete code. :
Sql query running in header :-
?php
error_reporting(0);
include_once('cc/connect.php');
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
$str="insert into registration(fname,lname,email,mobile_number,code,designation,organization,comps,city,affid,date_time,status)values('".mysql_escape_string($_POST['txtfname'])."','".mysql_escape_string($_POST['txtlname'])."','".mysql_escape_string($_POST['txtemail'])."','".mysql_escape_string($_POST['txtmobilenumber'])."','".mysql_escape_string($_POST['txtcode'])."','".mysql_escape_string($_POST['desig'])."','".mysql_escape_string($_POST['org'])."','".mysql_escape_string($_POST['comps'])."','".mysql_escape_string($_POST['txtcity'])."','".mysql_escape_string($_POST['txtaff'])."',now(),0)";
$rslt=mysql_query($str);
if(!$rslt)
{
echo '<script type="text/javascript">
alert("We are experiencing some issues, please try later");
</script>
';
}
else
{
echo '<script type="text/javascript">
window.location.href="thankyou.php";
</script>
';
}
}
?>
Javascript Validation :-
<script type="text/javascript">
function validate_form()
{
var pattern =/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var mob=/^(\+91[\-\s]?)?[89]\d{9}$/;
if(document.getElementById('txtfname').value=="" || document.getElementById('txtfname').value==null)
{
alert("Please enter First Name");
document.getElementById('txtfname').focus();
return false;
}
if(document.getElementById('txtlname').value=="" || document.getElementById('txtlname').value==null)
{
alert("Please enter Last Name");
document.getElementById('txtlname').focus();
return false;
}
if(document.getElementById('txtemail').value=="" || document.getElementById('txtemail').value==null)
{
alert("Please enter the Email");
document.getElementById('txtemail').focus();
return false;
}
if(!pattern.test(document.getElementById('txtemail').value))
{
alert("Please enter the valid Email");
document.getElementById('txtemail').focus();
return false;
}
if(document.getElementById('txtmobilenumber').value=="" || document.getElementById('txtmobilenumber').value==null)
{
alert("Please enter the Mobile Number");
document.getElementById('txtmobilenumber').focus();
return false;
}
if(document.getElementById('txtcode').value=="" || document.getElementById('txtcode').value==null)
{
alert("Please enter verification code");
document.getElementById('txtcode').focus();
return false;
}else
{
check_existence(document.getElementById('txtcode').value,6);
}
if(document.getElementById('comps').value=="" || document.getElementById('comps').value==null)
{
alert("Please enter Company strength");
document.getElementById('comps').focus();
return false;
}
if(!isNaN(document.getElementById('comps').value))
{
alert("Please select the valid Company strength");
document.getElementById('comps').value='';
document.getElementById('comps').focus();
return false;
}
if(document.getElementById('org').value=="" || document.getElementById('org').value==null)
{
alert("Please enter Organization");
document.getElementById('org').focus();
return false;
}
if(document.getElementById('txtcity').value=="" || document.getElementById('txtcity').value==null)
{
alert("Please enter the city");
document.getElementById('txtcity').focus();
return false;
}
if(!isNaN(document.getElementById('txtcity').value))
{
alert("Please enter the valid city");
document.getElementById('txtcity').value='';
document.getElementById('txtcity').focus();
return false;
}
}
function check_existence(val,caseno)
{
var pattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var mob=/^(\+91[\-\s]?)?[789]\d{9}$/;
var xmlhttp;
if(caseno=="1")
{
if(!pattern.test(document.getElementById('txtemail').value))
{
alert("Please enter the valid email");
document.getElementById('txtemail').value='';
document.getElementById('txtemail').focus();
return false;
}
}
if(caseno=="2")
{
if(!mob.test(document.getElementById('txtmobilenumber').value))
{
alert("Please enter the valid mobile number");
document.getElementById('txtmobilenumber').value='';
document.getElementById('txtmobilenumber').focus();
return false;
}
}
if(caseno=="3")
{
if(!mob1.test(document.getElementById('txtname').value))
{
alert("Please enter the valid mobile number");
document.getElementById('txtname').value='';
document.getElementById('txtname').focus();
return false;
}
}
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(xmlhttp.responseText=="1")
{
alert("Email address already exists");
document.getElementById('txtemail').value='';
document.getElementById('txtemail').focus();
}
if(xmlhttp.responseText=="2")
{
alert("Verification code has been sent to your mobile");
document.getElementById('txtcode').focus();
}
if(xmlhttp.responseText=="3")
{
document.forms["formsms"].submit();
}
if(xmlhttp.responseText=="4")
{
alert("Please enter the valid verification code");
document.getElementById('txtcode').focus();
}
if(xmlhttp.responseText=="5")
{
alert("Mobile Number already exists");
document.getElementById('txtmobilenumber').value='';
document.getElementById('txtmobilenumber').focus();
}
}
}
xmlhttp.open("GET","ajax_file.php?caseno="+caseno+"&val="+val,true);
xmlhttp.send();
}
</script>
Form Code :-
<div class="form-content">
<form class="form-box register-form form-validator" id="formsms" name="formsms" method="post">
<div class="form-group">
<label>First name: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtfname" id="txtfname" required>
</div>
<div class="form-group">
<label>Last name: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtlname" id="txtlname" required>
</div>
<div class="form-group">
<label>Email: <span class="required">*</span></label>
<input class="form-control" type="email" name="txtemail" id="txtemail" onchange="return check_existence(this.value,1);" required>
</div>
<div class="form-group">
<div style="float:left; width:270px;" >
<label>Mobile: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtmobilenumber" id="txtmobilenumber" onchange="return check_existence(this.value,2);" required>
</div>
<div style="float:right">
<label>Verification Code: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtcode" id="txtcode" required>
</div>
</div>
<div style="clear:both;"></div>
<div class="form-group">
<label>Select Graduation: <span class="required">*</span></label>
<select class="form-control" name="comps" id="comps">
<option>Select...</option>
<option value="BA">BA</option>
<option value="BBA">BBA</option>
<option value="BCom">BCom</option>
<option value="BSC">BSC</option>
<option value="BTech">BTech</option>
<option value="Other">Other</option>
</select>
</div>
<div class="form-group">
<label>Graduation%: <span class="required">*</span></label>
<input class="form-control" type="text" name="org" id="org" required>
</div>
<div class="form-group">
<label>City: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtcity" id="txtcity" required>
</div>
<div class="buttons-box clearfix">
<input type="button" id="btnsubmit" name="btnsubmit" class="btn btn-default" value="Submit" onclick="return validate_form()"/>
<span class="required"><b>*</b> Required Field</span>
<br>
</div>
</form><!-- .form-box -->
</div>
The simplest way is to use PHP sessions. These will store data from one interaction with the user, to be retrieved on another interaction.
In connect.php, add:
session_start();
In index.php, after you've validated and saved info in the DB, save the data that you want to pass between pages in the $_SESSION array
$_SESSION['fname'] = $_POST['txtfname'];
....
It's actually better to save things to session after you've done all string manipulation (eg: after applying mysql_escape_string).
Now, whenever the user makes another request, you can find the data in that same array. So on thankyou.php
$fname = $_SESSION['fname'];
...
Here is a basic intro to sessions.
This next note goes beyond your question but it's one really important lesson: sessions rely on cookies to recognize a user when he makes another visit. This means that a savvy user can manipulate this cookie and break his session or try to present himself as someone else in order to bypass your security restrictions. Once you're comfortable with the basics, look into how to use sessions securely!
This sounds like a typical case when $_SESSION may come in handy. In this Case (since you are doing your thing with AJAX), you may want to handle the Session in your AJAX Processing PHP File... (header.php?) Well here's how:
<?php
// FILE-NAME: header.php //<== THE AJAX PROCESSING SCRIPT
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
error_reporting(0);
include_once('cc/connect.php');
if($_SERVER['REQUEST_METHOD'] === 'POST') {
// JUST START SETTING UP THE SESSION DATA IF DATA WAS POSTED...
$_SESSION['fname'] = htmlspecialchars(trim($_POST['txtfname']));
$_SESSION['lname'] = htmlspecialchars(trim($_POST['txtlname']));
$_SESSION['email'] = htmlspecialchars(trim($_POST['txtemail']));
$_SESSION['mobile_number'] = htmlspecialchars(trim($_POST['txtmobilenumber']));
$_SESSION['code'] = htmlspecialchars(trim($_POST['txtcode']));
$_SESSION['designation'] = htmlspecialchars(trim($_POST['desig']));
$_SESSION['organization'] = htmlspecialchars(trim($_POST['org']));
$_SESSION['comps'] = htmlspecialchars(trim($_POST['comps']));
$_SESSION['city'] = htmlspecialchars(trim($_POST['txtcity']));
$_SESSION['affid'] = htmlspecialchars(trim($_POST['txtaff']));
$_SESSION['date_time'] = date("Y-m-d", time());
$_SESSION['status'] = "0";
$str="insert into registration(fname,lname,email,mobile_number,code,designation,organization,comps,city,affid,date_time,status)values('".mysql_escape_string($_POST['txtfname'])."','".mysql_escape_string($_POST['txtlname'])."','".mysql_escape_string($_POST['txtemail'])."','".mysql_escape_string($_POST['txtmobilenumber'])."','".mysql_escape_string($_POST['txtcode'])."','".mysql_escape_string($_POST['desig'])."','".mysql_escape_string($_POST['org'])."','".mysql_escape_string($_POST['comps'])."','".mysql_escape_string($_POST['txtcity'])."','".mysql_escape_string($_POST['txtaff'])."',now(),0)";
$rslt=mysql_query($str);
//... THE REST OF YOUR CODE...
}
Then, inside of thankyou.php, you can do this:
<?php
// FILE-NAME: thankyou.php
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
// TO GET THE EMAIL, FIRST & LAST NAMES HERE, YOU CAN SIMPLE DO LIKE SO:
$email = isset( $_SESSION['email'] )? $_SESSION['email'] : "";
$firstName = isset( $_SESSION['fname'] )? $_SESSION['fname'] : "";
$lastName = isset( $_SESSION['lname'] )? $_SESSION['lname'] : "";
// ASSUMING YOU WANT TO THANK THE USER BY NAME:
// YOU MAY DO SOMETHING LIKE SO:
$thankYou = "<div class='thank-you'>" . PHP_EOL;
$thankYou .= "<p class='appreciation'>Thank you, " ;
$thankYou .= "<span class='user-name'>{$firstName} {$lastName}</span>";
$thankYou .= " for your E-Mail... bla...bla..</p>" .PHP_EOL;
$thankYou = "</div>" . PHP_EOL;
echo $thankYou;
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;
}
Until now I have
HTML
<form id="account_reg" action="reg.php" method="post">
<div id="response"></div>
<div class="input">
<label>Login</>
<input name="login" type="text" class="required" id="login" size="30"/>
</div>
<div class="input">
<label>Password</>
<input name="password" type="text" class="required" id="password" size="30"/>
</div>
<div class="input">
<label>Repeat Password</>
<input name="rpassword" type="text" class="required" id="rpassword" size="30"/>
</div>
<div class="input">
<label>Email</>
<input name="email" type="text" class="required" id="email" size="30"/>
</div>
<div class="button">
<input type="submit" name="send" id="send" value="Send"/>
</div>
<div class="input">
<input type="hidden" name="honeypot" id="honeypot" value="http://"/>
<input type="hidden" name="humancheck" id="humancheck" class="clear" value=""/>
</div>
</form>
MY PHP
I have some validation on server side.
`
include("dop/config.php"); //includ Db connect
$login = ($_POST['login']);
$password = ($_POST['password']);
$rpassword = ($_POST['rpassword']);
$email = ($_POST['email']);
$humancheck = $_POST['humancheck'];
$honeypot = $_POST['honeypot'];
if ($honeypot == 'http://' && empty($humancheck)) {
$error_message = '';
$reg_exp = "/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9-]+\.[a-Za-Z.](2,4)$/";
if(!preg_match($reg_exp, $email)){
$error_message .="<p>A Valid email is required</p>";
}
if(empty($login)){
$error_message .="<p>enter login</p>";
}
if(empty($password)){
$error_message .="<p>Enter password</p>";
}
if(empty($rpassword)){
$error_message .="<p>Enter password again</p>";
}
if($password != $rpassword){
$error_message .="<p>password mut match</p>";
}
}
else {
$return['error'] = true;
$return['msg'] = "<h3>There was a problem with your submission. Please try again.</h3>";
echo json_encode($return);
}
My JS
With Validation.
$('#send').click(function(e)
{
e.preventDefault();
var valid = '';
var required =' is required.';
var login = $('#account_reg #login').val();
var password = $('#account_reg #password').val();
var rpassword = $('#account_reg #rpassword').val();
var email = $('#account_reg #email').val();
var honeypot = $('#account_reg #honeypot').val();
var humancheck = $('#account_reg #humancheck').val();
if(login = ''){
valid ='<p> Your Name '+ required +'</p>';
}
if(password='' || company.length<=6){
valid +='<p> Password '+ required +'</p>';
}
if(rpassword != password){
valid +='<p> password must match </p>';
}
if(!email.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i))
{
valid +='<p> Your Email' + required +'</p>';
}
if (honeypot != 'http://') {
valid += '<p>Spambots are not allowed.</p>';
}
if (humancheck != '') {
valid += '<p>A human user' + required + '</p>';
}
if(valid !=''){
$('#account_reg #response').removeClass().addClass("error")
.html('<strong> Please Correct the errors Below </strong>' + valid).fadeIn('fast');
}
else{
//$('form #response').removeClass().addClass('processing').html('Processing...').fadeIn('fast');
var formData = $('#account_reg').serialize();
$('#send').val("Please wait...");
submitForm(formData);
}
});
function submitForm(formData) {
$.post('reg2.php',formData, function(data){
//console.log(data);
$('#send').val("Send");
if (data === '1') {
alert('ok!');
} else {
alert('wrong shit');
}
});
};
I didn't do yet the MySQL part With Inserting and checking if account is already registered.
The first problem that I have is on Click event redirects me on reg.php even when I use e.preventDefault();
If anybody knows a good tutorial for creating registration form or any suggestion.
The form is submitted, that is why you get to reg.php. From what I see you are submitting the data with a custom function anyway so the quickest way to fix that would be to change the submit input into a regular button. So
<input type="submit" name="send" id="send" value="Send"/>
becomes
<input type="button" name="send" id="send" value="Send"/>
I think that it might also help if you return false when you find an error in the function that validates the form when.
A side question: I find it strange that you chose to have a honeypot field with a value (http://). Usually those fields are empty.. Is there any specific reason for doing so?
You need to keep all your JS code expect function submitForm(formData) inside $(document).ready(function(){});
If I'm not wrong there is no variable with name company so change this variable to password i,e. in second if condition of your validation.
Note: If some errors exist in your code then don't escape from those errors instead try to debug it.
there is something wrong with JS code when the code is not working
maybe you can try from this example for SignupForm using JQuery http://bit.ly/1aAXy5U
this is my first post and i'm rather new to php + ajax.
I have most of my coding set up only problem now is that when i press the submit button an notification shows up that only should show up when the text fields aren't empty.
This is my code:
<head><script>
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
alert("Thank you for subscribing to SHCA");
document.forms["ContactForm"].reset();
});
});
</script> </head>
followed by some php coding:
<?php
if(strlen($_POST['name']) > 0 AND strlen($_POST['email']) > 0)
{
if(isset($_POST['submit']))
{
$hostdb = '';
$namedb = '';
$userdb = '';
$passdb = '';
$conn = mysqli_connect($hostdb , $userdb, $passdb ,$namedb);
$sql = "INSERT INTO subscribers (name, email) VALUES('$_POST[name]', '$_POST[email]')";
if (!mysqli_query($conn, $sql))
{
die('Error: ' .mysql_error($conn));
}
if (!mysqli_ping($conn)) {
echo 'Lost connection, exiting after query #1';
exit;
}
mysqli_close($conn);
}}
else
{
?>
<form id="ContactForm" action="" method="post">
<label for="author">Name:</label> <input type="text" id="name" name="name" class="required input_field float_r" />
</br>
</br>
<label for="email">Email:</label> <input type="text" id="email" name="email" class="validate-email required input_field float_r" />
<div class="cleaner h10"></div>
<input type="submit" value="Subscribe" id="submit" name="submit" class="submit_btn float_l" />
</form>
<?php } ?>
hope anyone here is able to tell me what i should do to only show the "Thank you for subscribing to SHCA" message when the textfields aren't empty
final anwser Dereck forgot the '' in the objects so shout out to dereck for helping me!
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
if( !$('#name').val()) {
alert("please enter your name");
}
if(!$('#email').val()) {
alert("plese enter your email adress");
}
else{
alert("Thank you for subscribing to SHCA");
}
document.forms["ContactForm"].reset();
});
});
You need to check the contents of the fields before submitting to the server, a simple script method can check before you submit. If the fields are empty then display an error messge and don't submit the form.
function SubmitDetails()
{
if(window.ContactForm.name.value == "")
{
window.alert("Please enter a name");
return;
}if(window.ContactForm.email.value == "")
{
window.alert("Please enter an email" );
return;
}
window.ContactForm.submit();
}
This should do it without having to do a refresh
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
if( !$(#name).val() || !$(#email).val()) {
//don't display
}else{
alert("Thank you for subscribing to SHCA");
}
document.forms["ContactForm"].reset();
});
});