I have a site I'm working on Modestewebstudio.com
On the contact section of the site I have a form that I'm trying to submit using jQuery and pHp. For some reason the form does not submit. The validation works fine but whenever I hit submit nothing happens.
$(document).ready(function () {
$(window).load(function() { $("#load").fadeOut("slow"); });
var fadeInElement = function(id) {
$('#' + id).fadeIn();
};
//HOME-------------------------------------------------
$(".home").click(function () {
$('#about, #works, #contact').filter(":visible").fadeOut();
fadeInElement('home');
});
//ABOUT------------------------------------------------
$(".about").click(function () {
$('#home, #works, #contact').filter(":visible").fadeOut();
fadeInElement('about');
});
//WORKS------------------------------------------------
$(".works").click(function () {
$('#home, #about, #contact').filter(":visible").fadeOut();
fadeInElement('works');
});
//CONTACT----------------------------------------------
$(".contact").click(function () {
$('#home, #about, #works').filter(":visible").fadeOut();
fadeInElement('contact');
});
<!--//--><![CDATA[//><!--
$('form#contact-us').submit(function() {
$('form#contact-us .error').remove();
var hasError = false;
$('.requiredField').each(function() {
if($.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">Your '+labelText+' is missing.</span>');
$(this).addClass('inputError');
hasError = true;
} else if($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">Your '+labelText+' is invalid.</span>');
$(this).addClass('inputError');
hasError = true;
}
}
});
if(!hasError) {
var formInput = $(this).serialize();
$.post($(this).attr('action'),formInput, function(data){
$('form#contact-us').slideUp("fast", function() {
$(this).before('<p>Your email has been delivered!</p>');
});
});
}
return false;
});
//-->!]]>
//-----------------------------------------------------
});
<?php
error_reporting(E_ALL ^ E_NOTICE); // hide all basic notices from PHP
//If the form is submitted
if(isset($_POST['submitted'])) {
// require a name from user
if(trim($_POST['contactName']) === '') {
$nameError = 'Forgot your name!';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
// need valid email
if(trim($_POST['email']) === '') {
$emailError = 'Forgot to enter in your e-mail address.';
$hasError = true;
} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST['email']))) {
$emailError = 'You entered an invalid email address.';
$hasError = true;
} else {
$email = trim($_POST['email']);
}
// we need at least some content
if(trim($_POST['comments']) === '') {
$commentError = 'You forgot to enter a message!';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
// upon no failure errors let's email now!
if(!isset($hasError)) {
$emailTo = 'zenneson#gmail.com';
$subject = 'Submitted message from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From: ' .' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
// set our boolean completion value to TRUE
$emailSent = true;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Denneson Modeste</title>
<!--Fonts-->
<link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Syncopate' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Special+Elite' rel='stylesheet' type='text/css'>
<!--CSS-->
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div id="load">
<div class="load-logo pulse"></div>
<p>Loading</p>
</div>
<div class="tv"></div>
<div class="home tv-btn">HOME</div>
<div class="about tv-btn">ABOUT</div>
<div class="works tv-btn">WORKS</div>
<div class="blog tv-btn">BLOG</div>
<div class="contact tv-btn">CONTACT</div>
<div id="home" class="channel">
<iframe width="100%" height="100%" src="https://www.youtube.com/embed/JdRO97mFMx8?rel=0&controls=0&autoplay=1&showinfo=0&disablekb=1&disablekb=1&modestbranding=1&start=7&loop=1&playlist=JdRO97mFMx8&wmode=opaque" frameborder="0" allowfullscreen></iframe>
</div><!-- end of home -->
<div id="about" class="channel">
<iframe width="100%" height="100%" src="https://www.youtube.com/embed/JdRO97mFMx8?rel=0&controls=0&autoplay=1&showinfo=0&disablekb=1&disablekb=1&modestbranding=1&start=7&loop=1&playlist=JdRO97mFMx8&wmode=opaque" frameborder="0" allowfullscreen></iframe>
</div><!-- end of about -->
<div id="works" class="channel">
</div><!-- end of works -->
<div id="contact" class="channel">
<div class="contact-border"></div>
<div class="stamp"></div>
<div class="contact-section">
<h3>Have a question or wanna say hello? Leave a message below.</h3>
<?php if(isset($emailSent) && $emailSent == true) { ?>
<p class="info">Your message was sent and will be responded to ASAP.</p>
<?php } else { ?>
<form id="contact-us" action="contact.php" method="post">
<?php if(isset($hasError) || isset($captchaError) ) { ?>
<p class="alert">There was a mistake in the message</p>
<?php } ?>
<label>Name</label>
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="txt requiredField" placeholder="Name:" />
<?php if($nameError != '') { ?>
<br /><span class="error"><?php echo $nameError;?></span>
<?php } ?>
<label>E-mail</label>
<input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="txt requiredField email" placeholder="Email:" />
<?php if($emailError != '') { ?>
<br /><span class="error"><?php echo $emailError;?></span>
<?php } ?>
<label>Message</label>
<textarea name="comments" id="commentsText" class="txtarea requiredField" placeholder="Message:"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<?php if($commentError != '') { ?>
<br /><span class="error"><?php echo $commentError;?></span>
<?php } ?>
<button name="submit" type="submit" class="subbutton"> </button>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
</div><!-- end of contact-section -->
<?php } ?>
</div>
</div>
</div><!-- end of contact -->
<!--Javascript-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="js/application.js"></script>
</body>
</html>
Submitting the form results in the following error
404 (Not Found) http://modestewebstudio.com/contact.php
Make sure there that the file is in fact named contact.php, and that it's placed in the root directory of your web server.
Related
I made a chat service in php. When you get to the chat, it says "Welcome, --Username--." My problem is I added a login field, now I can't send messages and the username isn't displayed. I've looked everywhere but it seems since my code is so "unique", nothing seems to be helping. --i didn't make this all on my own, I used someone else's code for the login and someone's code for the service itself.
login.php
<?php
session_start();
echo isset($_SESSION['login']);
if(isset($_SESSION['login'])) {
header('LOCATION:admin.php'); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
if($username === 'admon' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
admin.php
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION:login.php'); die();
}
if(isset($_GET['logout'])){
//Simple exit message
$logout_message = "<div class='msgln'><span class='left-info'>User <b class='user-name-left'>". $_SESSION['name'] ."</b> has left the chat session.</span><br></div>";
file_put_contents("log.html", $logout_message, FILE_APPEND | LOCK_EX);
session_destroy();
header("Location: login.php"); //Redirect the user
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>English Pricks</title>
<meta name="description" content="A Group Chat." />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b><?php echo $username['username']; ?></b>. Image Dump...</p>
<p>Emoji's → </p>
<button id="emoji-button" style="border: none;">😀</button>
<p class="logout"><a id="exit" href="#">Leave</a></p>
</div>
<div id="chatbox">
<?php
if(file_exists("log.html") && filesize("log.html") > 0){
$contents = file_get_contents("log.html");
echo $contents;
}
?>
</div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" style="outline: none;" spellcheck="true"/>
<input name="submitmsg" type="submit" id="submitmsg" value="↑" />
</form>
</div>
<script type="text/javascript" src="./jquery.min.js"></script>
<script src="emoji.js"></script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var picker = new EmojiButton();
var button = document.querySelector('#emoji-button');
button.addEventListener('click', function () {
picker.showPicker(button);
picker.on('emoji', emoji => {
document.querySelector('#usermsg').value += emoji;
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#submitmsg").click(function(){
var clientmsg = $.trim($("#usermsg").val());
if(clientmsg.length >= 1){ // Prevents Spamming the Enter Key
$.post("post.php", {text: clientmsg});
$("#usermsg").val("");
}else{
}
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height before the request
$.ajax({
url: "log.html",
cache: false,
success: function (html) {
$("#chatbox").html(html); //Insert chat log into the #chatbox div
//Auto-scroll
var newscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height after the request
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
}
});
}
setInterval (loadLog, 1000);
$("#exit").click(function () {
var exit = confirm("Are you sure you want to leave?");
if (exit == true) {
window.location = "index.php?logout=true";
}
});
});
</script>
</body>
</html>
In login.php file else was missing in if blocks and in order to see username you should add it to $_SESSION in the same way as you did with
$_SESSION['login'], cause i don't see anything else which can serve as temp storage in provided code. Another issue is that you placed header() function with login and password check right inside html code. This will trigger warning on a runtime that headers were already sent. In order to avoid that place your checking code in the top of the file and also check if there are no spaces before or after <?php php opening tag.
Example of fixed login.php file you can find below.
<?php
session_start();
function setSessionData($name, $value) {
$_SESSION[$name] = $value;
}
function redirectWithData($username = '') {
setSessionData('login', true);
setSessionData('username', $username);
header('Location:admin.php');
die();
}
if(isset($_SESSION['login'])) {
header('Location:admin.php'); die();
}
if(isset($_POST['submit'])) {
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
redirectWithData($username);
} elseif($username === 'admon' && $password === 'password'){
redirectWithData($username);
} else {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
On admin page you can then display username
Welcome, <b><?php echo $_SESSION['username']; ?>
Regarding admin.php functionality. Logic for adding messages according to JavaScript code located in post.php file.
$.post("post.php", {text: clientmsg});
So, why its adding or not adding it is hard to answer for obvious reasons )
And btw, in your logout logic in admin.php file change
window.location = "index.php?logout=true"; -> window.location = "?logout=true"; it will fallback to the same page on which you already have redirect logic.
How I can hide this - "<div class="show1">" when user are not logged in and show only when user are logged in?
This is my code --->>>
<html><head>
<meta charset="utf-8">
<title>100% | Register</title>
<link rel="stylesheet" type="text/css" href="main/home.css"/>
<link rel="stylesheet" type="text/css" href="main/register.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script></head><body><div id="container">
<?php include 'header.php'; ?>
<br/><br/><div class="show1">TEXT</div><div class="show1">TEXT</div>
<div class="hidden1"><div class="right-login" id="container-login"><div id="palabi5px">
<form method="post" class="formpost" id="nonono">
<input type="text" class="username" name="username0" placeholder="Username" autocomplete="off">
<input type="password" class="password" name="password0" placeholder="********">
<button type="submit" name="login" class="loging">Login</button>
</form>
---------------------------------
<br/><br/>
Text!<br/><br/>
<br/>
---------------------------------
<br/><br/></div></div></div>
<?php include 'saites.php'; ?></body></html>
<?php
session_start();
require('connect.php');
$username0 = #$_POST['username0'];
$password0 = #$_POST['password0'];
if(isset($_POST['login'])){
if($username0 && $password0) {
$check = mysqli_query($connect," SELECT * FROM users WHERE username='".$username0."'");
$rows = mysqli_num_rows($check);
if(mysqli_num_rows($check) != 0){
while($row = mysqli_fetch_assoc($check)){
$db_username0 = $row['username'];
$db_password0 = $row['password'];
}
if($username0 == $db_username0 && ($password0) == $db_password0){
#$_SESSION["username"] = $username;
echo "<script type='text/javascript'>
$(document).ready(function(){
alert('page loaded'); // alert to confirm the page is loaded
$('.hidden1').hide(); //enter the class or id of the particular html element which you wish to hide.
$('.show1').show(); //SHOW
});
</script>";
}else{
echo "<script>{ alert('Your pass id wrong.');}</script>";
}
}else{
echo "<script>{ alert('Couldn't find username.');}</script>";
}
}else{
echo "<script>{ alert('Please fill in all the fields.');}</script>";
}
}
?>
<div class="show1">TEXT</div><div class="show1">TEXT</div>
Replace with following code
if(isset($_SESSION["username"])){
echo '<div class="show1">TEXT</div><div class="show1">TEXT</div>';
}
tutsplus, there you will find a tutorial which guides you through the steps on how to create a simple web chat. I tried to follow all that was said, yet I noticed a problem when testing. It seems that the usermsg is not being posted to the log.html file.
here is the index.php, which in this case is named chat.php:
<?php
function loginForm() {
echo '
<div id="loginform">
<form action="chat.php" method="post">
<p>Please enter your name to continue:</p>
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<input type="submit" name="enter" id="enter" value="enter">
</form>
</div>
';
}
if(isset($_POST['enter'])) {
if($_POST['name'] != "") {
$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
}else {
echo '<span class="error">Please type in a name</span>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Basic Chat Service</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" title="style" type="text/css" media="screen" charset="utf-8">
</head>
<body>
<?php
if(!isset($_SESSION['name'])) {
loginForm();
}else{
?>
<div id="wrapper">
<div id="menu">
<div class="welcome">Welcome, <?php echo $_SESSION["name"]; ?></div>
<div class="logout">Exit Chat</div>
<div style="clear:both;"></div>
</div>
<div id="chatbox"><?php
if(file_exists("log.html") && filesize("log.html") > 0) {
$handle = fopen("log.html", "r");
$contents = fread($handle, filesize("log.html"));
fclose($handle);
echo $contents;
}
?></div>
<form name="message" action="">
<input type="text" name="usermsg" id="usermsg" size="63">
<input type="submit" name="submitmsg" id="submitmsg" value="Send">
</form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript">
//jQuery Document
$(document).ready(function() {
$("#exit").click(function() {
var exit = confirm("Are you sure you want to logout?");
if(exit == true) {
window.location = 'chat.php?logout=true';
}
});
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
console.log(clientmsg);
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
$.ajax({
url:"log.html",
cache: false,
success: function(html){
$("#chatbox").html(html);
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight) {
$("#chatbox").animate({scrollTop: newscrollHeight}, 'normal');
}
}
});
}
setInterval(loadLog, 2500);
});
</script>
<?php
}
if(isset($_GET['logout'])) {
$fp = fopen("log.html", 'a');
fwrite($fp, '<div class="msgln"><i>User '.$_SESSION['name'].' has left the chat session.</i><br></div>');
fclose($fp);
session_destroy();
header("Location: chat.php");
}
?>
</body>
</html>
Here is the post.php:
<?php
session_start();
if(isset($_SESSION['name'])) {
$text = $_POST['text'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'>(".date("g:i A").")<b>".$_SESSION['name']."</b>:".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
I am using MAMP, and the files are located in the htdocs folder, so that's not the problem.
Thanks in advance for any help you can give me, and let me know if you need more info.
You should call session_start() in index.php.
(from Marc B in the comments)
im trying to set up a blind input field with php that will check and make sure the input field is empty and if it is not empty it will not send the message that it is set up to send but I've run into several problems with placement and wording of this here is my code any input would greatly be appreciated.
<?php
// Set email variables
$email_to = 'email#example.com';
$email_subject = 'Website Message';
// Set required fields
$required_fields = array('fullname','email','comment');
$fakes = array('Email1');
// set error messages
$error_messages = array(
'fullname' => 'Please enter a Name to proceed.',
'email' => 'Please enter a valid Email Address to continue.',
'comment' => 'Please enter your Message to continue.'
);
// Set form status
$form_complete = FALSE;
// configure validation array
$validation = array();
// check form submittal
if(!empty($_POST)) {
// Sanitise POST array
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
foreach($fakes as $fake)
if($fake == 'Email1') if(!check_for_content($_POST[$fake])) die;
else {
// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {
// the field has been submitted?
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
// check there is information in the field?
if($_POST[$field] == '') array_push($validation, $field);
// validate the email address supplied
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
// basic validation result
if(count($validation) == 0) {
// Prepare our content string
$email_content = 'New Website Comment: ' . "\n\n";
// simple email content
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
}
// if validation passed ok then send the email
mail($email_to, $email_subject, $email_content);
// Update form switch
$form_complete = TRUE;
}
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
function check_for_content($fake = FALSE) {
return (preg_match('[A-Z0-9._%+-]', $Email1))? TRUE : FALSE;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- Contact Form Designed by James Brand # dreamweavertutorial.co.uk -->
<!-- Covered under creative commons license - http://dreamweavertutorial.co.uk/permissions/contact-form-permissions.htm -->
<title>Contact Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/mootools/1.3.0/mootools-yui-compressed.js"></script>
<script type="text/javascript" src="validation/validation.js"></script>
<script type="text/javascript">
var nameError = '<?php echo $error_messages['fullname']; ?>';
var emailError = '<?php echo $error_messages['email']; ?>';
var commentError = '<?php echo $error_messages['comment']; ?>';
</script>
</head>
<body>
<div id="Contactus">
<p>Chisel Multimedia</p>
<p>275 Roswell Street NE <br />
Marietta GA 30060</p>
</div>
<br />
<div id="formWrap">
<div id="form">
<?php if($form_complete === FALSE): ?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" id="comments_form">
<div id="label1" 865style="display:none">
<div class="row">
<div class="label">Email</div>
<!-- end .label -->
<div class="input">
<input type="text" id="Email1" class="detail" name="Emial1" />
</div>
<!-- end .input -->
<div class="context">e.g. John Smith or Jane Doe</div>
<!-- end .context-->
</div>
<!-- end .row -->
</div>
<div class="row">
<div class="label">Your Name</div>
<!-- end .label -->
<div class="input">
<input type="text" id="fullname" class="detail" name="fullname" value="<?php echo isset($_POST['fullname'])? $_POST['fullname'] : ''; ?>" />
<?php if(in_array('fullname', $validation)): ?>
<span class="error"><?php echo $error_messages['fullname']; ?></span>
<?php endif; ?>
</div>
<!-- end .input -->
<div class="context">e.g. John Smith or Jane Doe</div>
<!-- end .context-->
</div>
<!-- end .row -->
<div class="row">
<div vlass="label">Your Email Address</div>
<!-- end .lable -->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />
<?php if(in_array('email', $validation)): ?>
<span class="error"><?php echo $error_messages['email']; ?></span>
<?php endif; ?>
</div>
<!-- end .input -->
<div class="context">abc#bca.com</div>
<!-- end .context-->
</div>
<!-- end .row -->
<div class="row">
<div vlass="label">Your Message</div>
<!-- end .lable -->
<div class="input">
<textarea id="comment" name="comment" class="mess"><?php echo isset($_POST['comment'])? $_POST['comment'] : ''; ?></textarea>
<?php if(in_array('comment', $validation)): ?>
<span class="error"><?php echo $error_messages['comment']; ?></span>
<?php endif; ?>
</div>
<!-- end .input -->
</div>
<!-- end .row -->
<div class="submit">
<input type="submit" id="submit" name="submit" value="Send Message" />
</div>
<!-- end submit -->
</form>
<?php else: ?>
<p style="font-size: 10px; color: #255e67; width: 65%;">Thank you for your Message!</p>
<?php endif; ?>
</div>
<!-- end form -->
</div>
<!-- end formWrap -->
</body>
</html>
You have to much errors in your code, that prevents you from getting correct results
<input type="text" id="Email1" class="detail" name="Emial1" />
Pay attention, that name="Emial1", but in php code you check for 'Email1'. Correct one of those.
Next piece:
function check_for_content($fake = FALSE) {
return (preg_match('[A-Z0-9._%+-]', $Email1))? TRUE : FALSE;
}
Using $Email1 variable is just out of place. Regex expression is lack of boundaries. At least it should be
function check_for_content($fake = FALSE) {
return (preg_match('/[A-Z0-9._%+-]/i', $fake))? TRUE : FALSE;
}
And when you calling this function why Not condition?
if($fake == 'Email1') if(!check_for_content($_POST[$fake])) die();
I think it should be vice versa.
Anyway, personally I'll just use something like this:
foreach($fakes as $fake)
if(!empty($_POST[$fake])) { die();}
// dont need 'else'
Also when debugging your php code, make sure you turn on errors, it realy helps
error_reporting(0);
ini_set('display_errors', 0);
this is my main.php
<?php
session_start();
if (!isset($_SESSION['username']))
{
header('Location: index.php');
}
include("connection/config.php");
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>TOM ELOY CONVENIENCE STORE</title>
<link rel="stylesheet" href="css/design.css" type="text/css" />
<link href="css/style.css" media="screen" rel="stylesheet" type="text/css" />
<link href="css/iconic.css" media="screen" rel="stylesheet" type="text/css" />
<script></script>
</head>
<body>
<div id="wrapper">
<!--header link -->
<div id="sitename" class="clear">
<?php include_once("header.php"); ?>
</div>
<!--menu navigation -->
<div class="wrap">
<nav>
<?php include_once("menunav.php"); ?>
<div class="clearfix"></div>
</nav>
</div>
<div id="body-wrapper">
<!-- body -->
<div id="body" class="clear">
<div class="clear">
<div id="content"></div>
<!-- script for pages -->
<script type="text/javascript" src="js/general.js"></script>
<script src="js/main.js"></script>
</div>
</div>
</div>
<!--footer link -->
<div id="footer" align="center">
<?php include_once("footer.php"); ?>
</div>
</div>
</body>
</html>
this is my javascript the main.js
$(document).ready(function () {
$('#content').load('main2.php');
$('ul#nav li a').click(function() {
var page = $(this).attr('href');
$('#content').load( page + '.php');
return false;
});
});
this is my supplierprofile.php
<?php
session_start();
if (!isset($_SESSION['username']))
{
header('Location: index.php');
}
include("connection/config.php");
?><html>
<head>
<link rel="stylesheet" href="css/styles.css" type="text/css" />
<!-- autorefresh of the table -->
<script type="text/javascript">
function Ajax()
{
var
$http,
$self = arguments.callee;
if (window.XMLHttpRequest) {
$http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
$http = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {
$http = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ($http) {
$http.onreadystatechange = function()
{
if (/4|^complete$/.test($http.readyState)) {
document.getElementById('ReloadThis').innerHTML = $http.responseText;
setTimeout(function(){$self();}, 0);
}
};
$http.open('GET', 'supplierprofiletable.php' + '?' + new Date().getTime(), true);
$http.send(null);
}
}
</script>
</head>
<!-- content2 -->
<div id="content">
<p id="bcp">Browse Supplier Profile</p><br><br>
<ul id="nav">
<li>
<a id="abutton">PRINT</a>
<a id="abutton" href="addspform">ADD SUPPLIER</a>
</li>
</ul>
<!-- autorefresh of the table -->
<script type="text/javascript">
setTimeout(function() {Ajax();}, 0);
</script>
<!-- table to be refresh -->
<div id="ReloadThis"><?php include_once("supplierprofiletable.php"); ?></div>
</div>
<? -- script for pages --?>
<script type="text/javascript" src="js/general.js"></script>
<script src="js/submain.js"></script>
this is the supplieprofiletable.php
<table id="spvt" align="center">
<tr>
<th id="spvth">SUPPLIER NAME</th>
<th id="spvth">TERMS DAY</th>
<th id="spvth">VAT</th>
<th id="spvth">MODIFY</th>
<th id="spvth">DELETE</th>
</tr>
<?php
include("connection/config.php");
$sql = "select * from SUPPLIER_PROFILE ORDER BY SP_NAME";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<tr id='spvtr'>";
echo "<td id='spvtd' style='text-align:left;'>" . $row['SP_NAME'] . "</td>";
echo "<td id='spvtd'>" . $row['SP_TERMS_DAY'] . "</td>";
echo "<td id='spvtd'>" . $row['SP_VAT'] . "</td>";
echo "<td id='spvtd'>MODIFY SUPPLIER</td>";
echo "<td id='spvtd'>DELETE SUPPLIER</td>";
echo "</tr>";
}
?>
this is the addspform.php
<head>
<link rel="stylesheet" href="css/design.css" type="text/css" />
<link href="style.css" media="screen" rel="stylesheet" type="text/css" />
<link href="iconic.css" media="screen" rel="stylesheet" type="text/css" />
<script type = "text/javascript">
<!--
var run1 = function()
{
var x1 = document.addsp.spname.value.length;
if(x1 == 0)
{
alert("SUPPLIER NAME SHOULD NOT BE EMPTY");
return(false);
}
else
return(true);
}
var run2 = function()
{
var x1 = document.addsp.spadd.value.length;
if(x1 == 0)
{
alert("SUPPLIER ADDRESS SHOULD NOT BE EMPTY");
return(false);
}
else
return(true);
}
var run3 = function()
{
var x1 = document.addsp.sptd.value.length;
if(x1 == 0)
{
alert("SUPPLIER TERMS DAY SHOULD NOT BE EMPTY");
return(false);
}
else
return(true);
}
var run4 = function()
{
var x1 = document.addsp.spvat.value.length;
if(x1 == 0)
{
alert("SUPPLIER VAT SHOULD NOT BE EMPTY");
return(false);
}
else
return(true);
}
function checkall()
{
if(run1() == false)
{
addsp.spname.focus();
return(false);
}
if(run2() == false)
{
addsp.spadd.focus();
return(false);
}
if(run3() == false)
{
addsp.sptd.focus();
return(false);
}
if(run4() == false)
{
addsp.spvat.focus();
return(false);
}
if(/^[0-9]+$/i.test(addsp.sptd.value) == false)
{
alert("invalid Terms Day");
addsp.sptd.focus();
return(false);
}
else
{
return(true);
}
}
-->
</script>
</head>
<!-- body -->
<div id="content">
<div class="clear">
<p id="bcp">ADD Supplier</p><br><br>
<ul id="nav">
<li>
<a id="abutton" href="supplierprofile">VIEW SUPPLIER</a>
</li>
</ul>
<br>
<form id="aft" name ="addsp" action = "addsp.php" method = "post" onsubmit = "return checkall();">
<fieldset>
<legend>SUPPLIER FORM (NEW)</legend>
<table>
<tr><td>
<span style = "width: 50px;" >Supplier Name</span>
</td><td>
<input size="100" type = "text" name = "spname" onkeyup = "this.value = this.value.toUpperCase();" value =""/><br />
</td></tr>
<tr><td>
<span style = "width: 100px;">Address</span>
</td><td>
<input size="100" type = "text" name = "spadd" value = "" /><br />
</td></tr>
<tr><td>
<span style = "width: 120px;">Telephone No.</span>
</td><td>
<input size="100" type = "text" name = "sptelno" value = "" /><br />
</td></tr>
<tr><td>
<span style = "width: 100px;">Terms Day</span>
</td><td>
<input size="100" type = "text" name = "sptd" value = "" /><br />
</td></tr>
<tr><td>
<span style = "width: 100px;">VAT</span>
</td><td>
<select name="spvat">
<option id="o1"> </option>
<option id="o2">INCLUSIVE</option>
<option id="o3">EXCLUSIVE</option>
</select>
</td></tr>
<tr><td></td><td>
<input class="afbutton" type = "submit" name = "ADD" value = "ADD" id="ADD"/>
</td></tr>
<tr><td>
</table>
</fieldset>
</form>
</div>
</div>
<? -- script for pages --?>
<script type="text/javascript" src="js/general.js"></script>
<script src="js/submain.js"></script>
this is the addsp.php
<html>
<head>
<script type="text/javascript">
<!--
function direct()
{
window.alert("Suppler has been added");
w = window || document
w.location.reload();
}
-->
</script>
</head>
<body>
<?php
include("connection/config.php");
$spname = $_POST['spname'];
$spadd = $_POST['spadd'];
$sptelno = $_POST['sptelno'];
$sptd = $_POST['sptd'];
$spvat = $_POST['spvat'];
if(!$_POST['ADD'])
{
echo "Please fill out the form";
header('Location: addspform.php');
}
else
{
$query = "SELECT * FROM supplier_profile WHERE sp_name = '$spname'";
$result = mysql_query($query)or die(mysql_error());
$counter = 0;
while($supplier = mysql_fetch_array($result))
{
$counter = $counter + 1;
}
if($counter == 0)
{
mysql_query("INSERT INTO supplier_profile(`SP_NAME`,`SP_ADDRESS`, `SP_TELNO`,`SP_VAT`,`SP_TERMS_DAY`)
VALUES('$spname','$spadd','$sptelno','$spvat','$sptd')") or die(mysql_error());
echo '<script type="text/javascript">
direct();
</script>';
}
}
?>
</body>
sorry about the previous information. Now if i click the add button to the addspform.php all i want after the javascript that pop-up and click ok is to direct the supplierprofile.php inside in the main.php
make your addsp.php like this
<?php
session_start();
include("connection/config.php");
$spname = $_POST['spname'];
$spadd = $_POST['spadd'];
$sptelno = $_POST['sptelno'];
$sptd = $_POST['sptd'];
$spvat = $_POST['spvat'];
if(!$_POST['ADD'])
{
$_SESSION['msg'] = "Please fill form";
header('Location: addspform.php');
exit;
}
else
{
$query = "SELECT * FROM supplier_profile WHERE sp_name = '$spname'";
$result = mysql_query($query)or die(mysql_error());
$counter = 0;
while($supplier = mysql_fetch_array($result))
{
$counter = $counter + 1;
}
if($counter == 0)
{
mysql_query("INSERT INTO supplier_profile(`SP_NAME`,`SP_ADDRESS`, `SP_TELNO`,`SP_VAT`,`SP_TERMS_DAY`)
VALUES('$spname','$spadd','$sptelno','$spvat','$sptd')") or die(mysql_error());
$_SESSION['msg'] = "form has been submitted successfully";
header('Location: addspform.php');
exit;
}
}
?>
you can use header function of php to redirect on some page. use session as msg and print it on your form page as follows
<?php
session_start();
if(isset($_SESSION['msg']))
{
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
?>
<form id="aft" name ="addsp" action = "addsp.php" method = "post" onsubmit = "return checkall();">
<fieldset>
<legend>SUPPLIER FORM (NEW)</legend>
<table>
<tr><td>
<span style = "width: 50px;" >Supplier Name</span>
</td><td>
<input size="100" type = "text" name = "spname" onkeyup = "this.value = this.value.toUpperCase();" value =""/><br />
</td></tr>
<tr><td>
<span style = "width: 100px;">Address</span>
</td><td>
<input size="100" type = "text" name = "spadd" value = "" /><br />
</td></tr>
<tr><td>
<span style = "width: 120px;">Telephone No.</span>
</td><td>
<input size="100" type = "text" name = "sptelno" value = "" /><br />
</td></tr>
<tr><td>
<span style = "width: 100px;">Terms Day</span>
</td><td>
<input size="100" type = "text" name = "sptd" value = "" /><br />
</td></tr>
<tr><td>
<span style = "width: 100px;">VAT</span>
</td><td>
<select name="spvat">
<option id="o1"> </option>
<option id="o2">INCLUSIVE</option>
<option id="o3">EXCLUSIVE</option>
</select>
</td></tr>
<tr><td></td><td>
<input class="afbutton" type = "submit" name = "ADD" value = "ADD" id="ADD"/>
</td></tr>
<tr><td>
</table>
</fieldset>
</form>
redefine direct as:
function direct(){
window.alert("Suppler has been added");
w = window || document
w.location.reload();
}
Just do a redirect in addsp.php
if (test){
//do something
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=yourpage.php">';//This causes the browser to open the new page after 0 seconds, i.e immediately.
} else {
return false;
}
http://php.about.com/od/learnphp/ht/phpredirection.htm
//addsp.php
function direct()
{
window.alert("Suppler has been added");
document.location.href = "main.php?page='pagenamewhichlastloaded'&redirect=1";
}
//main.php
$(function(){
if($("#redirect").val() == 1){
var page = $("#page").val();
$('#content').load( page + '.php');
}
$('ul#nav li a').click(function() {
var page = $(this).attr('href');
$('#content').load( page + '.php');
return false;
});
});
<div id="content"></div>
<input type="hidden" id="page" value="<?php if(isset($_POST['page'])){ echo $_POST['page']; }?>" />
<input type="hidden" id="redirect" value="<?php if(isset($_POST['redirect'])){ echo $_POST['redirect']; }?>" />