Ajax script not calling - javascript

Inside my page it works, doesn't refresh the page and it sends to the database exactly how I want it, however, when it sends, or has an error depending on the error it should highlight the box but it doesn't. Whenever I press the button I get this error in the console:
index.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("form").submit(function(){
event.preventDefault();
var name = $("#mail-name").val();
var email = $("#mail-email").val();
var gender = $("#mail-gender").val();
var message = $("#mail-message").val();
var submit = $("#mail-sendEmail").val();
$(".form-message").load("mail.php", {
name: name,
email: email,
gender: gender,
message: message,
submit: submit
})
});
});
</script>
</head>
<body>
<form method="POST" action="mail.php">
<input type="text" name="name" id="mail-name" placeholder="Full name" value=""><br>
<input type="text" name="email" id="mail-email" placeholder="Email" value=""><br>
<select name="gender" id="mail-gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select><br>
<textarea name="message" id="mail-message" placeholder="Message" rows="8" cols="80"></textarea><br>
<button type="submit" name="sendEmail" id="mail-sendEmail">Send email</button>
<p class="form-message"></p>
</form>
</body>
</html>
mail.php
<?php
include('inc/db.php');
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$gender = $_POST['gender'];
$message = $_POST['message'];
$errorEmpty = false;
$errorEmptyName = false;
$errorEmptyEmail = false;
$errorEmptyMessage = false;
$errorEmail = false;
if(empty($name) || empty($email) || empty($message)){
$errorEmpty = true;
if(empty($name)){
echo "<span class='form-error'> Please enter a name! </span><br>";
$errorEmptyName = true;
}
if(empty($email)){
echo "<span class='form-error'> Please enter an email! </span><br>";
$errorEmptyEmail = true;
}
if(empty($message)){
echo "<span class='form-error'> Please enter a message! </span><br>";
$errorEmptyMessage = true;
}
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "<span class='form-error'> Please enter a valid email! </span><br>";
$errorEmail = true;
}else{
echo "<span class='form-success'> Successfully sent! </span><br>";
DB::query('INSERT INTO contact VALUES(\'\', :name, :email, :gender, :message)', array(':name'=>$name, ':email'=>$email, ':gender'=>$gender, ':message'=>$message));
}
}else{
die("Error");
}
?>
<script>
$("#name, #email, #message, #gender").removeClass("input-error");
var $errorEmpty = "<?php echo "$errorEmpty" ?>";
var errorEmptyName = "<?php echo $errorEmptyName ?>";
var errorEmptyEmail = "<?php echo $errorEmptyEmail ?>";
var errorEmptyMessage = "<?php echo $errorEmptyMessage ?>";
var errorEmail = "<?php echo $errorEmail ?>";
if(errorEmpty == true){
if(errorEmptyName == true){
$("#name").addClass("input-error");
}
if(errorEmptyEmail == true){
$("#email").addClass("input-error");
}
if(errorEmptyMessage == true){
$("#message").addClass("input-error");
}
}else if(errorEmail == true){
$("#email").addClass("input-error");
}
if(errorEmpty == false && errorEmail == false){
$("#name, #email, #message").val('');
}
</script>
It doesn't call the script inside the mail.php script.

Related

Opening a .html with window.location

I'm writing a simple login page in Ajax + Jquery
I have an error when I click on the button. And I don't understand why.
Uncaught SyntaxError: Unexpected end of input
At this line
echo '<input type="button" value="connexion" OnClick="window.location.assign("http://localhost/loginmap/members/success.html")>';
There is my code
<?php
session_start();
//si le user a un session de ouverte
/*if(isset($_SESSION['connecté'])){
header('Location : success.html');
die();
}*/
if (isset($_POST['login'])) {
$connection = new mysqli('localhost','root','','monumap');
$email = $connection->real_escape_string($_POST['emailPHP']);
$password = $connection->real_escape_string($_POST['passwordPHP']);
$data = $connection->query("SELECT id FROM users WHERE email = '$email' AND password = '$password'");
if($data->num_rows >= 0) {//tout et ok -> connexion
$_SESSION['connecté'] = '1';
//$_SESSION['email'] = $email;
header('Location:'.$_SESSION['redirectURL']);
exit('<font color = "green">Connexion reussi...</font>');
}else{
exit('<font color = "red">Le Mot de passe / Email est inconnue </font>');
}
//exit($email . " = " . $password);
}
?>
<html>
<head>
<title>Monumap Connexion</title>
</head>
<body>
<form method="post" action="login.php">
<input type="text" id="email" placeholder="Email..."><br>
<input type="password" id="password" placeholder="Mot de passe..."><br>
<input type="submit" value="Log In" id="login">
</form>
<p id = "reponse"></p>
<div class="Bouton">
<?php if($_SESSION['connecté']==1){
echo '<input type="button" value="connexion" OnClick="window.location.assign("http://localhost/loginmap/members/success.html")>';
}
?>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#login").on('click', function () {
var email = $("#email").val();
var password = $("#password").val();
if (email == "" || password == "")
alert('vos inputs sont vides');
else {
$.ajax(
{
url: 'login.php',
method: 'POST',
data: {
login: 1,
emailPHP: email,
passwordPHP: password
},
success: function (reponse) {
$("#reponse").html(reponse);
},
dataType: 'text'
}
);
}
});
});
</script>
</body>
</html>
echo '<input type="button" value="connexion" onclick="window.location.assign('."'http://localhost/loginmap/members/success.html'".');")/>';
It's cause you wrote quote character.
You can use this way as well.
echo '<input type="button" value="connexion" onclick="func()"/>';
?>
<script>
function func(){
window.location.assign("http://localhost/loginmap/members/success.html");
}
</script>

How can i make a form that saves text in database and uploads a file on server

Ok so I am trying to make a form for a prison visit. I must save in an oracle database the first name, last name, id, inmate code, relationship, purpose of visit, date, hour and the name of the image. Moreover I need to upload the image on the server. I have made 2 forms and 2 php files that process the 2 forms and a javascript button that send them both but the second PHP which works with the picture loads after the first one so the errors from the first one don't appear. I tried to put the code from the second in the first one but still nothing. Can you please tell me how can I do to solve this? Below there is my code. The name of the inputs are in romanian but if you look at the form and the php you will figure it out. Here is the code:
Html file:
<!DOCTYPE html>
<html>
<head>
<title>CerereVizita</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="cerereV.css">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0">
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="jquery.min.js"></script>
<script src="jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$("#datepicker").datepicker();
});
</script>
</head>
<body>
<div class="Container">
<img src="persoana2.png" alt="Avatar" class="avatar">
<div class="Container2">
<iframe name="votar" style="display:none;"></iframe>
<form action="cerereVizita.php" method="POST" id="form1" target="votar">
<label><b>Nume:</b></label>
<input type="text" placeholder="Ex: Popescu" name="last name" required>
<label><b>Prenume:</b></label>
<input type="text" placeholder="Ex: Marius" name="prenume" required>
<label><b>CNP:</b></label>
<input type="text" placeholder="Ex: 1900101125356" name="cnp" required>
<label><b>Cod Detinut:</b></label>
<input type="text" placeholder="Ex: 1234" name="cod-detinut" required>
<label><b>Tipul de relatie:</b></label>
<input type="text" placeholder="Ex: Sot" name="relatie" required>
<label><b>Natura vizitei:</b></label>
<input type="text" placeholder="Ex: Discutie" name="natura-vizitei" required>
<label><b>Data:</b></label>
<input id="datepicker" name="data" required>
<label for="myList"> <b>Ora:</b></label>
<div>
<select name="ora" id = "myList" form="form1" required>
<option value = "12:00">12:00</option>
<option value = "13:00">13:00</option>
<option value = "14:00">14:00</option>
<option value = "15:00">15:00</option>
</select>
</div>
</form>
<form action="testU.php" method="post" enctype="multipart/form-data" target="votar">
<label> <b>Poza:</b>
<input type="file" name="fileToUpload" id="fileToUpload">
</label>
</form>
<button onclick="submitForms()">Submit!</button>
</div>
<div class="item">
<h3> Va rugam completati toate spatiile si verificati de 2 ori inainte sa trimiteti! </h3>
</div>
<div class="Container3">
FAQ
Contact
</div>
<img class="Poza" src="asd.jpg" alt="Prison image">
</div>
</body>
</html>
<script language="javascript">
function submitForms(){
$('form').submit();
}
</script>
Php for form1:
<?php
//Oracle DB user name
$username = 'TW';
// Oracle DB user password
$password = 'TW';
// Oracle DB connection string
$connection_string = 'localhost/xe';
//Connect to an Oracle database
$connection = oci_connect(
$username,
$password,
$connection_string
);
$var1 = $_POST['nume'];
$var2 = $_POST['prenume'];
$var3 = $_POST['cnp'];
$var4 = $_POST['cod-detinut'];
$var5 = $_POST['relatie'];
$var6 = $_POST['natura-vizitei'];
$var7 = $_POST['data'];
$var8 = $_POST['ora'];
if(is_numeric($var4)==true) {
//stid4
$stid4 = oci_parse($connection, 'SELECT COUNT(ID) as "count" FROM DETINUTI WHERE ID=:codD');
if (!$stid4) {
$e = oci_error($connection);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
oci_bind_by_name($stid4, ':codD', $var4);
$r4 = oci_execute($stid4);
if (!$r4) {
$e = oci_error($stid4);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$row4 = oci_fetch_array($stid4, OCI_ASSOC + OCI_RETURN_LOBS);
$count2 = $row4['count'];
if (is_numeric($var3) == true AND strlen($var3) == 13) {
//stid2
$stid2 = oci_parse($connection, 'SELECT COUNT(*) AS "count" FROM CEREREVIZITE WHERE CNP = :cnp AND DATA_VIZITA = to_date(:data_vizita,\'MM/DD/YYYY\')');
if (!$stid2) {
$e = oci_error($connection);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
oci_bind_by_name($stid2, ':cnp', $var3);
oci_bind_by_name($stid2, ':data_vizita', $var7);
$r2 = oci_execute($stid2);
if (!$r2) {
$e = oci_error($stid2);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$row2 = oci_fetch_array($stid2, OCI_ASSOC + OCI_RETURN_LOBS);
$count = $row2['count'];
//stid3
$stid3 = oci_parse($connection, 'SELECT MAX(ID) AS "ID" FROM CEREREVIZITE');
if (!$stid3) {
$e = oci_error($connection);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$r3 = oci_execute($stid3);
if (!$r3) {
$e = oci_error($stid3);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$row3 = oci_fetch_array($stid3, OCI_ASSOC + OCI_RETURN_LOBS);
$max = $row3['ID'];
if ($count2 == 0) {
$message = "Detinutul cu id-ul " . $var4 . " nu exista.";
echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
} else {
if ($count == 0) {
//stid1
$stid1 = oci_parse($connection, 'INSERT INTO CEREREVIZITE VALUES (:id+1,:nume,:prenume,:cnp,:cod_detinut,:relatie,:natura,to_date(:data_vizita,\'MM/DD/YYYY\'),:ora,\'poza\')');
if (!$stid1) {
$e = oci_error($connection);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
oci_bind_by_name($stid1, ':id', $max);
oci_bind_by_name($stid1, ':nume', $var1);
oci_bind_by_name($stid1, ':prenume', $var2);
oci_bind_by_name($stid1, ':cnp', $var3);
oci_bind_by_name($stid1, ':cod_detinut', $var4);
oci_bind_by_name($stid1, ':relatie', $var5);
oci_bind_by_name($stid1, ':natura', $var6);
oci_bind_by_name($stid1, ':data_vizita', $var7);
oci_bind_by_name($stid1, ':ora', $var8);
$r1 = oci_execute($stid1);
if (!$r1) {
$e = oci_error($stid1);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$message = "Datele au fost inregistrate cu succes. ";
echo "<script type='text/javascript'>alert('$message'); window.location.href = \"guest.html\";</script>";
} else {
$message = "Aveti deja o vizita inregistrata in data de " . $var7;
echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
}
}
} else {
$message = "CNP invalid.";
echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
}
}
else{
$message = "Cod invalid! ";
echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
}
oci_close($connection);
?>
Php for form2 (aka picture upload form):
<?php
$target_dir = "C:/Apache24/htdocs/dwnds/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$message = "File is an image - " . $check["mime"] . ".";
echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
$uploadOk = 1;
} else {
$message = "File is not an image.";
echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
$message = "Sorry, file already exists.";
echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
$message = "Sorry, your file is too large.";
echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$message = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$message = "Sorry, your file was not uploaded.";
echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$message = "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
echo "<script type='text/javascript'>alert('$message'); window.location.href = \"guest.html\";</script>";
} else {
$message = "Sorry, there was an error uploading your file.";
echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
}
}
?>
There is no need to use two html forms and two php files. You can combine two forms. Just add enctype="multipart/form-data" when you are transmitting files using html form as you have done in the 2nd form. It will look like this -
<form action="cerereVizita.php" method="POST" id="form1" target="votar" enctype="multipart/form-data">
<label><b>Nume:</b></label>
<input type="text" placeholder="Ex: Popescu" name="last name" required>
<label><b>Prenume:</b></label>
<input type="text" placeholder="Ex: Marius" name="prenume" required>
<label><b>CNP:</b></label>
<input type="text" placeholder="Ex: 1900101125356" name="cnp" required>
<label><b>Cod Detinut:</b></label>
<input type="text" placeholder="Ex: 1234" name="cod-detinut" required>
<label><b>Tipul de relatie:</b></label>
<input type="text" placeholder="Ex: Sot" name="relatie" required>
<label><b>Natura vizitei:</b></label>
<input type="text" placeholder="Ex: Discutie" name="natura-vizitei" required>
<label><b>Data:</b></label>
<input id="datepicker" name="data" required>
<label for="myList"> <b>Ora:</b></label>
<div>
<select name="ora" id="myList" form="form1" required>
<option value = "12:00">12:00</option>
<option value = "13:00">13:00</option>
<option value = "14:00">14:00</option>
<option value = "15:00">15:00</option>
</select>
</div>
<label> <b>Poza:</b></label>
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
After this combine your PHP logic in one file.

php simple contact form - stop submit on page refresh

The following PHP form works without any issues other than on refresh. If a user hits the refresh button after submitting the form, it re-submits the form.
Is there a way to use PHP or Jquery to stop the form re-submitting after refreshing the page?
I know in PHP there should be a way with Session, but I am not sure how.
contact.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.error_message{color:#cc0000;}
.form1{}
.form2{display:none;}
#succsess_page h1{background:url('http://example.com/ok.png')left no-repeat;padding-left:40px;color:#45a015; }
</style>
<h1>This is a simple contact form</h1>
<?php
//fields
$link_address = 'contact.php'; // page to redirect to
$honeypot = '';
$error = '';
$name = 'Name';
$email = 'Email';
$comments = 'Message';
if(isset($_POST['contactus'])) {
$honeypot = $_POST['email_confirm'];
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
// honeypot
if($honeypot)
exit(1);
//error messages
if(trim($name) == 'Name') {
$error = '<div class="error_message">Need your Name</div>';
} else if(trim($name) == '') {
$error = '<div class="error_message">Need your Name</div>';
} else if(trim($email) == 'Email') {
$error = '<div class="error_message">Need your Email</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Need your Email</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Need a valid email</div>';
} else if(trim($comments) == 'Message') {
$error = '<div class="error_message">A Message is required</div>';
} else if(trim($comments) == '') {
$error = '<div class="error_message">A Message is required</div>';
}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
//email address
$address = "email#example.com";
//email message
$e_subject = 'Web Message from: ' . $name . '.';
$e_body = "From: $name\nEmail: $email \r\n\nMessage:\n$comments\n\n\n";
$msg = $e_body . $e_content . $e_reply;
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
{
//success html page response
echo "<div id='succsess_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you. The following was sent to us. <br/><br/>$name<br/><br/>$email<br/><br/>$comments</p>";
echo "<a href='$link_address'>CLOSE THIS MESSAGE</a>";
echo "</div>";
} else echo "Error. Mail not sent";
}
}
if(!isset($_POST['contactus']) || $error != '') // Do not edit.
{
?>
<?php echo $error; ?>
<!--form-->
<form method="post" action="" id="myform">
<p class="form1">Name: <input name="name" type="text" id="name" size="30" class="input1" value="<?php echo $name; ?>" onfocus="if(this.value == 'Name') { this.value = ''; }" onblur="toUpper(this.value); if(this.value == '') { this.value = 'Name'; }" value="Name" /></p>
<p class="form1">Email: <input name="email" type="text" id="email" size="30" class="input2" value="<?php echo $email; ?>" onfocus="if(this.value == 'Email') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Email'; }" value="Email" /></p>
<p class="form2">Confirm Email: <input name="email_confirm" type="text" id="email_confirm" size="30" value="<?php echo $email_confirm; ?>" /></p>
<p class="form1">Message: <textarea name="comments" cols="40" rows="3" id="comments" value="<?php echo $comments; ?>" onfocus="if(this.value == 'Message') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Message'; }" value="Message"><?php echo $comments; ?></textarea></p>
<p class="form1"><input name="contactus" type="submit" class="submit" id="contactus" value="Submit" /></p>
</form>
<!--end form-->
<?php }
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,12})$/",$email));
}
?>
<!------- capitalize first letter Name input ---->
<script>
function toUpper(mystring) {
var sp = mystring.split(' ');
var wl=0;
var f ,r;
var word = new Array();
for (i = 0 ; i < sp.length ; i ++ ) {
f = sp[i].substring(0,1).toUpperCase();
r = sp[i].substring(1);
word[i] = f+r;
}
newstring = word.join(' ');
document.getElementById('name').value = newstring;
return true;
}
</script>
After the form has been submitted correctly run the following code:
header("Location :contact.php?msg=success");
This will redirect the user back to the contact form with an condition allowing for a message to be displayed.
if($_REQUEST['msg']){
echo "Contact Form Submitted Successfully!!";
}
If they hit refresh it will just bring up a successful message while displaying the contact form again.
Update:
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
{
header("Location: contact.php?msg=success");
}else{
header("Location: contact.php?msg=error");
}
Then for displaying:
<?php if($_REQUEST['msg']=="success"){
echo "Success Message Here.";
}elseif($_REQUEST['msg']=="error"){
echo "Error Message Here."
}
<!--form-->
<form method="post" action="" id="myform">

Clear PHP Form after submission

O.k I have seen similar questions but can't seem to make it work. I would like that when the form is submitted the fields get cleared.
This is my PHP:
<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "EMAIL ADDRESS";
$subject = "Unriddle contact form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo '<p style="margin-top: 1em; font-color: #66CC00;">Thank you!</p>'; ?>
This my HTML:
<form action="mail.php" method="post">
<a class="form-row">
<p>Name</p>
<input id="iname" type="text" class="text-input required default" name="name" value="" />
</a>
<a class="form-row">
<p>Email</p>
<input id="email" type="text" class="text-input required email default" name="email" value="" />
</a>
<a class="form-row">
<p>Message</p>
<textarea id="message" class="text-area" name="message" cols="40" rows="8"></textarea>
</a>
<br />
<input class="btn-submit" type="submit" value="Send" name="submit" />
This is my JS
jQuery(document).ready(function($) {
var $loading = $('<div class="loading"><img src="/js/loading.gif" alt="" /></div>');
$(".default").each(function(){
var defaultVal = $(this).attr('title');
$(this).focus(function(){
if ($(this).val() == defaultVal){
$(this).removeClass('active').val('');
}
});
$(this).blur(function() {
if ($(this).val() == ''){
$(this).addClass('active').val(defaultVal);
}
})
.blur().addClass('active');
});
$('.btn-submit').click(function(e){
var $formId = $(this).parents('form');
var formAction = $formId.attr('action');
defaulttextRemove();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
$('li',$formId).removeClass('error');
$('span.error').remove();
$('.required',$formId).each(function(){
var inputVal = $(this).val();
var $parentTag = $(this).parent();
if(inputVal == ''){
$parentTag.addClass('error').append('<span class="error">Required field</span>');
}
if($(this).hasClass('email') == true){
if(!emailReg.test(inputVal)){
$parentTag.addClass('error').append('<span class="error">Enter a valid email address</span>');
}
}
});
if ($('span.error').length == "0") {
$formId.append($loading.clone());
$('fieldset',$formId).hide();
$.post(formAction, $formId.serialize(),function(data){
$('.loading').remove();
$formId.append(data).fadeIn();
});
}
e.preventDefault();
});
});
function defaulttextRemove(){
$('.default').each(function(){
var defaultVal = $(this).attr('title');
if ($(this).val() == defaultVal){
$(this).val('');
}
});
}
Is there a simple way of doing this ? What line of code do I need to add and where ? If you can help me that would be great, but please be specific as to where I should add the line of code.
Power to you! Thanks
Add reset on success of your ajax request or if you want to clear every time on submit add at the end .
if ($('span.error').length == "0") {
$formId.append($loading.clone());
$('fieldset',$formId).hide();
$.post(formAction, $formId.serialize(),function(data){
$('.loading').remove();
$formId.append(data).fadeIn();
$formId.reset();// to reset
});
}

JQuery/PHP form not Submiting

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.

Categories