I am looking to create a contact Us form in my website, where after the form is submitted, the text fields should be cleared, and a Thank You should appear.
Here is the html code :
<div class="form">
<div id="sendmessage">Your message has been sent. Thank you!</div>
<form action="contactform.php" method="post" role="form" class="contactForm">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Name (eg: James)" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Email (eg: james#example.com)" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Phone Number (eg: 0406 624 456)" data-rule="minlen:9" data-msg="Please enter a valid contact number" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<br/>
<div class="text-center">
<button type="submit" name="submit" value="Submit"></button>
<!--b>Send Message</b-->
</div>
</form>
The relevant java script code:
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.contactForm').submit(function(){
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function(){ // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if( rule !== undefined ){
var ierror=false; // error flag for current input
var pos = rule.indexOf( ':', 0 );
if( pos >= 0 ){
var exp = rule.substr( pos+1, rule.length );
rule = rule.substr(0, pos);
}else{
rule = rule.substr( pos+1, rule.length );
}
switch( rule ){
case 'required':
if( i.val()==='' ){ ferror=ierror=true; }
break;
case 'minlen':
if( i.val().length<parseInt(exp) ){ ferror=ierror=true; }
break;
case 'email':
if( !emailExp.test(i.val()) ){ ferror=ierror=true; }
break;
case 'checked':
if( !i.attr('checked') ){ ferror=ierror=true; }
break;
case 'regexp':
exp = new RegExp(exp);
if( !exp.test(i.val()) ){ ferror=ierror=true; }
break;
}
i.next('.validation').html( ( ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '' ) ).show('blind');
}
});
f.children('textarea').each(function(){ // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if( rule !== undefined ){
var ierror=false; // error flag for current input
var pos = rule.indexOf( ':', 0 );
if( pos >= 0 ){
var exp = rule.substr( pos+1, rule.length );
rule = rule.substr(0, pos);
}else{
rule = rule.substr( pos+1, rule.length );
}
switch( rule ){
case 'required':
if( i.val()==='' ){ ferror=ierror=true; }
break;
case 'minlen':
if( i.val().length<parseInt(exp) ){ ferror=ierror=true; }
break;
}
i.next('.validation').html( ( ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '' ) ).show('blind');
}
});
if( ferror ) return false;
else var str = $(this).serialize();
$.ajax({
// alert("enterd the loop")
type: "POST",
url: "contactform/contactform.php",
data: str,
success: function(msg){
//alert(msg);
if(msg == "New record created successfully") {
$("#sendmessage").addClass("show");
$("#errormessage").removeClass("show");
$('.contactForm').find("input, textarea").val("");
document.getElementsByClassName("contactForm").reset();
}
else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
}
});
return false;
});
});
Relevant php script to obtain db credentials and properties:
<?php include "../../inc/dbinfo.inc"; ?>
<?php
$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
$database = mysqli_select_db($connection, DB_DATABASE);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$Phone = test_input($_POST["Phone"]);
$message = test_input($_POST["message"]);
$submit = test_input($_POST["Submit"])
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$sql = "INSERT INTO contact_details (name, email, Phone, message)
VALUES ('$name', '$email', '$Phone', '$message')";
// <script>alert("your message is sent successfully");
// window.location="index.html";
// </script>
if ($connection->query($sql) === TRUE) {
echo "New record created successfully";
mysqli_free_result($result);
mysqli_close($connection);
} else {
echo "Error: " . $sql . "<br>" . $connection->error;
mysqli_free_result($result);
mysqli_close($connection);
}
?>
after submitting the form, the form doesn't reset and displays any message but its getting updated in the database.
Redirect to new page or same page like below:
if ($connection->query($sql) === TRUE) {
mysqli_free_result($result);
mysqli_close($connection);
header('Location: filename?msg=success');
}
Related
I'm attempting to create a page that allows the manipulation of an uploaded image by using Canvas. So far, I've had no luck forwarding the image from one page (the submit form) to the other, which contains the canvas. I'm using PHP, Javascript and HTML in order to try and send the image from the submit form to the canvas space.
This is the submitting form.
<form action="designer.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name</label><?php
include('/tbp3/php/autoload.php');
header('Content-Type: application/json');
$fullpath = $_SESSION['activeImg'];
$size = getimagesize($fullpath);
echo json_encode(array('x' => $size[0], 'y' => $size[1], 'path' => $fullpath, 'lastPosJson' => isset($_SESSION['lastPos']) ? $_SESSION['lastPos'] : '[]'));
$db->close();
?>
<p>2-32 characters</p>
<input class="form-control" type="text" name="name" id="name">
</div>
<div class="form-group">
<p>JPEG/PNG under 2MB only</p>
<label class="btn btn-default" for="image">Choose Image</label>
<span></span>
<input class="inputfile" type="file" name="image" id="canvas">
</div>
<div class="form-group">
</div>
<input class="btn btn-primary" type="submit" value="Next">
</form>
This is the JavaScript I use in order to confirm the uploaded file is a PNG or JPEG. Note: I'm a novice at Javascript.
var validTypes = ['png', 'jpg', 'jpeg'];
$(document).ready(function(){
$('form').submit(function(e){//on submission..
var file = $('#upload').val();
var isValid = true;
var error = '';
if(file == ''){
error = 'Select a file before proceeding!';
$('#upload').addClass('validation-error');
isValid = false;
} else{
var type = /[^\.]*$/.exec(file).toString().toLowerCase();
if($.inArray(type, validTypes) == -1){
error = type + ' is an invalid type for the image! Please use ' + validTypes.join(', ').replace(/,([^,]*)$/, " or$1.");
$('#upload').addClass('validation-error');
isValid = false;
}
}
});
And this is on the page 'Designer.php'. I want the image to be displayed on the tag.
<div class="row canvasarea">
<div class="col-xs-6 header">Canvas</div>
<div class="col-xs-6 header">Live View</div>
</div>
<div class="row canvasarea">
<div class="col-xs-6 help">TEXT</div>
<div class="col-xs-6 help">TEXT</div>
</div>
<div class="row canvasarea">
<div class="col-xs-6">
<canvas id='canvas'></canvas></div>
<div class="col-xs-6">
<img id='liveupdate'/><br></div>
The PHP script I'm using to save it to the server.
<?php
require('/var/www/html/tpb3/php/autoload.php');
session_start();
$megabyte = 8000000;
$db = "new Database();";
function getImage(){
$id = $this->getTemplateId();
$type = $this->getFiletype();
return "img/template/$id.$type";
}
function addTemplate($templateId, $filetype){
if(!$this->isLoggedIn()){
echo "You're not logged in";
return '';
}
function isValidFileType($type){
$type = strtolower($type);
$types = array('jpeg', 'jpg', 'png');
for($i = 0; $i < count($types); $i++){
if($type === $types[$i]){
return true;
}
}
return false;
}
function isPng($filepath){
$img = #imagecreatefrompng($filepath);
if($img === false){
return false;
} else{
echo "Not a PNG";
imagedestroy($img);
return true;
}
}
function isJpeg($filepath){
$img = #imagecreatefromjpeg($filepath);
if($img === false){
return false;
} else{
echo "Not a JPEG";
imagedestroy($img);
return true;
}
}
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
if(!empty($_POST['selectedType']) ){
$selectedType = $_POST['type'];
}
if(isset($_POST["type"]))
$selectedType = $_POST["type"];
$dir = $selectedType == 'template' ? 'temp' : 'sourceimages';
if(isset($_POST["submit"])) {
$valid = true;
$id = uniqid();
$type = strtolower(pathinfo(basename($_FILES['upload']['name']), PATHINFO_EXTENSION));
$uploadFileDest = 'img/template/$id.$type';
$size = #getimagesize($_FILES["upload"]["tmp_name"]);
$error = '';
if($size === false) {
$error .= "Main image not a valid image, ";
$valid = false;
} elseif($size[0] > 2000 || $size[1] > 2000){
$error .= "Image larger than 2000px, ";
$valid = false;
} elseif(!isValidFileType($type)){
$error .= "Not a valid filetype, ";
$valid = false;
} elseif(!isJpeg($_FILES["upload"]["tmp_name"]) && !isPng($_FILES["upload"]["tmp_name"])){
$error .= "Image is not a valid jpg/png. ";
$valid = false;
} elseif ($_FILES["upload"]["size"] > 2 * $megabyte) {
$error .= "File larger than 2 MB, ";
$valid = false;
}
}
if($valid = true){
if($selectedType == 'template'){
$_SESSION['activeId'] = $id;
$_SESSION['activeImg'] = $uploadFileDest;
move_uploaded_file($_FILES["upload"]["tmp_name"], $uploadFileDest);
header('Location: designer.php');
} else{
$response = $db->addSourceImage($id, $type);
if($response == ';success'){
move_uploaded_file($_FILES["upload"]["tmp_name"], $uploadFileDest);
$_SESSION['lastId'] = $id;
header('Location: success.php');
} else{
header('Location: submit.php?e='.urlencode("Database failed with message: $response"));
}
}
} else{
header('Location: submit.php?e='.urlencode(substr($error, 0, strlen($error) - 2)));
}
}
?>
Any push into the right direction would be appreciated.
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
Is my code ok to send and email using PHP? Please take a look:
HTML:
<form class="contact_form" method="POST" action="mail.php">
<div class="input">
<label class="pl">Imię</label>
<input id="name" type="text" name="name">
</div>
<div class="input">
<label>E-mail</label>
<input id="email" type="text" name="email">
</div>
<div class="input">
<label class="pl">Temat</label>
<input id="subject" type="text" name="subject">
</div>
<div class="message">
<label class="pl">Twoja wiadomość</label>
<textarea id="message" name="message"></textarea>
</div>
<div class="input">
<input id="submit_pl" class="button pl" type="submit" value="Wyślij">
<input id="reset_pl" class="button pl" type="reset" value="Resetuj">
</div>
</form>
JS/JQuery:
// Form Validation ------------------------------------ //
// Form is not valid on page load //
var isFormValid = false;
// input variables //
var name = $('#name');
var email = $('#email');
var subject = $('#subject');
var message = $('#message');
var subtmitBtnPl = $('#submit_pl');
var subtmitBtnEn = $('#submit_eng');
var resetBtnPl = $('#reset_pl');
var resetBtnEn = $('#reset_eng');
var form = $('.contact_form');
var isNameValid = function () {
var nameVal = name.val();
return nameVal.length > 0 && nameVal.length <= 100;
};
var isEmailValid = function () {
var emailVal = email.val();
return emailVal.indexOf('#') > -1 && emailVal.length <= 100;
};
var isSubjectValid = function () {
var subjectVal = subject.val();
return subjectVal.length > 0 && subjectVal.length <= 100;
};
var isMessageValid = function () {
var messageVal = message.val();
return messageVal.length > 0 && messageVal.length <= 500;
};
function formValidation() {
var isFormValid = isNameValid() && isEmailValid() && isSubjectValid() && isMessageValid();
if (isFormValid === false) {
alert('error');
} else {
alert('succes');
form[0].reset();
}
};
form.submit(function(event) {
event.preventDefault();
formValidation();
});
PHP:
<?php
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['subject'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$body = $_POST['message'];
$to = 'xyz#gmail.com';
//headers
$headers = "From: ".$name." <".$email.">\r\n";
$headers .= "Reply-To: ".$email."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset-utf-8";
//send
$send = mail($to, $subject, $body, $headers);
if ($send) {
echo '<br>';
echo 'Thanks for contacting me. I will be with You shorty.';
} else {
echo 'error';
}
}
?>
I'm very unexperienced with PHP. Could You please tell me why my contact form is not working/sending emails?
JQuery Validation works fine.
This project is just on my drive not localhost (is it ok for PHP mail() to work?).
Of course PHP file has name "mail.php".
install a web server like XAMPP,WAMPP, etc
I have a problem with form. After i click Dodaj button nothing happens.
I've putted alert dialog to see when it stops and it stops after
$.post('dodaj_ztoner.php', post_data, function(response){
I have made similar forms with similar code (names and number of items was different) and it worked
alert('post'); is not displaying. so looks like problem is here $.post('dodaj_ztoner.php', post_data, function(response){
html code:
<body>
<div id="dialog" title="Błąd Wprowadzania!">
<p>Proszę uzupełnić podświetlone pola.</p>
</div>
<div class="container">
<fieldset id="contact_form">
<h2>Zużycie Tonera</h2>
<div id="zresult"></div>
<label for="id"><span>ID</span></label>
<input type="text" name="zid" id="zid" value="<?php
$zapytanie = "select max(id) as id from zuzycie_toner";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo $wynik['id']+1;
}
mysql_free_result($widok);
?>" disabled />
<label for="zdata"><span>Data wydania</span></label>
<input type="text" name="zdata" id="zdata" />
<label for="ilwyd"><span>Ilość wydrukowanych</span> </label>
<input type="text" name="ilwyd" id="ilwyd" />
<label for="drukarka"><span>Drukarka</span></label>
<select type="text" name="zdrukarka" id="zdrukarka" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwa from drukarki order by nazwa";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[nazwa]</option>";
}
mysql_free_result($widok);
?>
</select>
<label for="toner"><span>Toner</span></label>
<select type="text" name="ztonery" id="ztonery" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwa from tonery order by nazwa";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[nazwa]</option>";
}
mysql_free_result($widok);
?>
</select>
<label for="user"><span>Użytkownik</span> </label>
<select type="text" name="zuser" id="zuser" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwisko_imie as id from uzytkownicy order by nazwisko_imie";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[id]</option>";
}
mysql_free_result($widok);
?>
</select>
<label><span> </span>
<button type="submit" class=submit_btn" id="zsubmit_btn">Dodaj</button>
</label>
JavaScript:
<script type="text/javascript">
$(document).ready(function() {
var divObj = $('#dialog');
divObj.dialog({
autoOpen: false
}
);
$( "#zdrukarka" ).selectmenu();
$( "#zuser" ).selectmenu();
$( "#ztonery" ).selectmenu();
$("#zdata").datepicker();
$( "button[type=submit]" )
.button()
$("#zsubmit_btn").click(function() {
//Pobieramy dane
var ztoner_id = $('input[name=zid]').val();
var ztoner_data = $('input[name=zdata]').val();
var ztoner_wydr = $('input[name=ilwyd]').val();
var ztoner_toner = $('select[name=ztonery]').val();
var ztoner_user = $('select[name=zuser]').val();
var ztoner_drukarka = $('select[name=zdrukarka]').val();
//Prosta walidacja (kolorujemy na czerwono pole jeśli jest puste
var proceed = true;
alert( '1');
//wszystko w porządku idziemy dalej
if(proceed)
{
//Dane do wysłania
post_data = {'ztonerID':ztoner_id, 'ztonerWydr':ztoner_wydr, 'ztonerData' :ztoner_data, 'ztonerToner' :ztoner_toner,
'ztonerUser':ztoner_user, 'ztonerDrukarka':ztoner_drukarka};
//Przesłanie danych poprzez AJAX
$.post('dodaj_ztoner.php', post_data, function(response){
alert( 'post');
//wczytanie danych zwrotnych JSON
if(response.type == 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
}
$("#zresult").hide().html(output).slideDown();
}, 'json');
} else divObj.dialog("open");
});
//resetujemy kolorowanie po zaczęciu pisania
});
</script>
PHP file:
<?php
include './includes/html_elements.php';
//pokaz_zmienna($_SERVER);
$db_link = connect_db();
if(!$db_link)
{
$out='<p>Brak połączenia z bazą danych</p>';
print_page($out, 'Baza książek');
exit;
}
if($_POST)
{
//Sprawdzamy czy jest to rządanie Ajax, jeśli nie..
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//Kończymy skrypt wysyłając dane JSON
$output = json_encode(
array(
'type'=>'error',
'text' => 'Rządanie musi przejść przez AJAX'
));
die($output);
}
//Sprawdzamy czy wszystkie pola zostały wysłane. kończymy skrypt jeśli nie (tutaj dodawaj więcej pól, które są wymagane)
if(!isset($_POST["ztonerID"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'POLA SĄ PUSTE!'));
die($output);
}
//Pobieramy dane z formularza
$ztoner_id = filter_var($_POST["ztonerID"], FILTER_SANITIZE_STRING);
$ztoner_data = filter_var($_POST["ztonerData"], FILTER_SANITIZE_STRING);
$ztoner_wydr = filter_var($_POST["ztonerWydr"], FILTER_SANITIZE_STRING);
$ztoner_drukarka = filter_var($_POST["ztonerDrukarka"], FILTER_SANITIZE_STRING);
$ztoner_toner = filter_var($_POST["ztonerToner"], FILTER_SANITIZE_STRING);
$ztoner_user = filter_var($_POST["ztonerUser"], FILTER_SANITIZE_STRING);
//Dodatkowa validacja PHP (tylko dla pól wymaganych)
if(!is_numeric($ztoner_id)) //sprawdzamy czy telefon jest numeryczny
{
$output = json_encode(array('type'=>'error', 'text' => 'Tylko liczby są dozwolone'));
die($output);
}
die($output);
}
$zapytanie = "select idd from drukarki where nazwa = '$ztoner_drukarka'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_drukarka = $wynik['idd'];
}
mysql_free_result($widok);
$zapytanie = "select idu from uzytkownicy where nazwisko_imie = '$ztoner_user'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_user = $wynik['idu'];
}
mysql_free_result($widok);
$zapytanie = "select idt from tonery where nazwa = '$ztoner_toner'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_toner = $wynik['idt'];
}
mysql_free_result($widok);
$insert = "Insert INTO zuzycie_toner Values ($ztoner_id, '$ztoner_data', $ztoner_wydr, $ztoner_drukarka, $ztoner_toner, '$ztoner_user')";
$wykonaj = mysql_query($insert);
if ($wykonaj)
{
$output = json_encode(array('type'=>'message', 'text' => 'Dodano '.$drukarki_nazwa.' do tabeli'));
die($output);
}else{
$output = json_encode(array('type'=>'error', 'text' => 'Dodawanie nie powiodło się '.$insert));
die($output);
}
}
?>
Your page doesn't conatains any form tag, so simple use
<button class=submit_btn" id="zsubmit_btn">Dodaj</button> instead of input type = submit
This will Work!!!!
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i have a script which I have been following a tutorial - I wish to remove the email activation and ensure the users are activated once they hit sign up instead of the activation email being sent and verified?
Here is the script.
<?php
session_start();
// If user is logged in, header them away
if(isset($_SESSION["username"])){
header("location: message.php?msg=NO to that weenis");
exit();
}
?><?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
include_once("includes/db_connex.php");
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
?><?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// CONNECT TO THE DATABASE
include_once("includes/db_connex.php");
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
$p_hash = md5 ($p);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (username, email, password, gender, country, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p_hash','$g','$c','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir('user/'.$u, 0755, True);
}
// Email the user their activation link
$to = "$e";
$from = "hello#iamdanbarrett.com";
$subject = 'yoursitename Account Activation';
$message = 'message here!'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
?>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[" "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else if( _("terms").style.display == "none"){
status.innerHTML = "Please view the terms of use";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText.replace(/^\s+|\s+$/g, " ") == "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g);
}
}
function openTerms(){
_("terms").style.display = "block";
emptyElement("status");
}
/* function addEvents(){
_("elemID").addEventListener("click", func, false);
}
window.onload = addEvents; */
</script>
</head>
<body>
<div id="pageMiddle">
<h3>Sign Up Here</h3>
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
<?php include_once("includes/template_country_list.php"); ?>
</select>
<div>
<a href="#" onclick="return false" onmousedown="openTerms()">
View the Terms Of Use
</a>
</div>
<div id="terms" style="display:none;">
<h3>Web Intersect Terms Of Use</h3>
<p>1. Play nice here.</p>
<p>2. Take a bath before you visit.</p>
<p>3. Brush your teeth before bed.</p>
</div>
<br /><br />
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
To be honest, you should really learn what is going on in the code instead of simply copying it out from a tutorial
The email activation occurs here
// Email the user their activation link
$to = "$e";
$from = "hello#iamdanbarrett.com";
$subject = 'yoursitename Account Activation';
$message = 'message here!'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
so you can simply remove this, and instead of emailing them a verification, just change their status in the database to registered or however you distinguish between someone who hasn't activated their account and someone who has activated their account.
In order to achieve that you'll need to :
1 - learn PHP
2 - There's no 2, you'll just figure it out once you can read the code.
So I've been attempting to get this page to work correctly for the past few days. As far as the database manipulation and what not it works like a charm. The problem is that it apparently isn't hitting my javascript function to redirect back onto itself. It will instead show a mostly blank page with no $_GET variables in the url which leads me to believe the problem is actually in my php function rather than my javascript function.
function edit_player()
{
try{
if( isset( $_GET['player_id'] ) )
{
if( isset( $_GET['success'] ) && $_GET['success'] )
{
echo "<div class='success'> You have successfully edited this players info.</div>" ;
}
$playerid = $_GET['player_id'] ;
$db = honneyconnect( ) ; // db connection established
if( mysqli_connect_error() )
{
throw new Exception( "Could not connect to the database") ;
}
$query = 'select * from roster where player_number ="'.$playerid.'"' ;
$player = $db->query( $query ) ;
if( !$player )
{
throw new Exception ( "Query returned zero results" ) ;
}
else
{
$row = $player->fetch_row() ;
echo '
<div class="data_entry">
<form id="player_info" method="post" action="editplayer.php" enctype="multipart/form-data" />
<input type="hidden" name="MAX_FILE_SIZE" value="50000000" />
<input type="hidden" name="player_number" value="'.$row[0].'" />
<table>
<tr><td>Player Number:</td><td>'.$row[0].'</td></tr>
<tr><td>Player Name:</td><td><input type="text" size="50" name="name" value="'.$row[1].'"/></td></tr>
<tr><td>Player Position:</td><td><input type="text" size="20" name="position" value="'.$row[2].'" /></td></tr>
<tr><td>Years Skating:</td><td><input type="text" size="3" name="years" value="'.$row[3].'"/></td></tr>
<tr><td>How You Chose Your Derby Name:</td><td><input type="text" size="100" name="choice" value="'.$row[4].'" /></td></tr>
<tr><td>Life Outside of Derby:</td><td><input type="text" size="100" name="life" value="'.$row[5].'" /></td></tr>
<tr><td>Current Photo: </td><td><img class="thumbnail" src="rosterpics/'.$row[6].'"></td></tr>
<tr><td>Choose a different photo:</td><td><input type="file" name="photo" id="photo" /></td></tr>
<tr><td>Sponsor:</td><td><input type="text" size="50" name="sponsors" value="'.$row[7].'"/></td></tr>
</table>
<input type="submit" value="Submit Data" />
</form></div>' ;
}
}
else
{
if( isset($_POST['player_number']) && isset($_POST['name']) && isset($_POST['position'])
&& isset($_POST['years']) && isset($_POST['choice']) && isset($_POST['life']) )
{
if( !file_exists( $_FILES['photo']['tmp_name'] ) || !is_uploaded_file($_FILES['photo']['tmp_name'] ) )
{
$db = honneyconnect( ) ; // db connection established
if( mysqli_connect_error() )
{
throw new Exception( "Could not connect to the database") ;
}
$query = 'update roster set player_name = "'.$_POST['name'].'" ,
player_position = "'.$_POST['position'].'", player_years = "'.$_POST['years'].'" , player_choice = "'.$_POST['choice'].'",
player_life = "'.$_POST['life'].'" where player_number = "'.$_POST['player_number'].'"' ;
$player = $db->query( $query ) ;
if( !$player )
{
throw new Exception( "Query failed" ) ;
}
else
{
if( isset($_POST['sponsors']) )
{
$query = 'update roster set player_sponsor = "'.$_POST['sponsors'].'" where player_number = "'.$_POST['player_number'].'"';
$sponsor = $db->query( $query ) ;
if( !$sponsor )
{
throw new Exception( "Failed to update sponsor." ) ;
}
else
{
$url = "http://localhost/honeysproject/editplayer.php?player_id=".$_POST['player_number']."" ;
echo "<script type='text/javascript'>success_redirect( ".$url." ) ;</script>" ;
}
}
else
{
$url = "http://localhost/honeysproject/editplayer.php?player_id=".$_POST['player_number']."" ;
echo "<script type='text/javascript'>success_redirect( ".$url." ) ;</script>" ;
}
}
}
else
{
if( $_FILES['photo']['size'] > 50000000 )
{
throw new Exception( "File is to large for this server." );
}
if( !move_uploaded_file($_FILES["photo"]["tmp_name"], "C:/wamp/www/HoneysProject/rosterpics/" . $_FILES["photo"]["name"]) )
{
throw new Exception( "There was a problem uploading the file" ) ;
}
else
{
$db = honneyconnect( ) ; // db connection established
if( mysqli_connect_error() )
{
throw new Exception( "Could not connect to the database") ;
}
$query = 'update roster set player_name = "'.$_POST['name'].'" ,
player_position = "'.$_POST['position'].'", player_years = "'.$_POST['years'].'" , player_choice = "'.$_POST['choice'].'",
player_life = "'.$_POST['life'].'", player_photo = "'.$_FILES['photo']['name'].'" where player_number = "'.$_POST['player_number'].'"' ;
$player = $db->query( $query ) ;
if( !$player )
{
throw new Exception( "Query failed" ) ;
}
else
{
if( isset($_POST['sponsors']) )
{
$query = 'update roster set player_sponsor = "'.$_POST['sponsors'].'" where player_number = "'.$_POST['player_number'].'"';
$sponsor = $db->query( $query ) ;
if( !$sponsor )
{
throw new Exception( "Failed to update sponsor." ) ;
}
else
{
$url = "http://localhost/honeysproject/editplayer.php?player_id=".$_POST['player_number']."" ;
echo "<script type='text/javascript'>success_redirect( ".$url." );</script>" ;
}
}
else
{
$url = "http://localhost/honeysproject/editplayer.php?player_id=".$_POST['player_number']."" ;
echo "<script type='text/javascript'>success_redirect( ".$url." ) ;</script>" ;
}
}
}
}
}
}
}
catch( Exception $error )
{
echo "<div class='error'>".$error."</div>" ;
echo $_FILES['photo']['name'] ;
}
}
<html>
<head>
<style>
#import "honeysstyle.css";
</style>
<script type="text/javascript">
function success_redirect( url )
{
window.location.replace( url ) ;
}
</script>
</head>
<body>
<?php
require( 'function.php' );
draw_masthead();
edit_player() ;
?>
</body>
</html>
success_redirect( ".$url." )
should be
success_redirect( '".$url." ')
and why don't you use the header function
header("Location: $url");