I have code that is supposed to post a file to a php using js. It is not working. I have previously attempted to view the image that is being sent. This has not worked. Incase anyone wanted to view what the code does, this is a sample login: username:john & password:1234.If anyone could help me, thanks in advance.
This is the html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.13.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyCg8CauUyZeBGffR_2yAv7hkb-pD9zuzrA",
authDomain: "push-notifications-affa8.firebaseapp.com",
databaseURL: "https://push-notifications-affa8.firebaseio.com",
projectId: "push-notifications-affa8",
storageBucket: "push-notifications-affa8.appspot.com",
messagingSenderId: "1027448457059"
};
firebase.initializeApp(config);
</script>
<link rel="manifest" href="/manifest.json">
<title>MegaLords</title>
<link rel="stylesheet" href="styles/main.css">
<style>
#fileToUpload {
display:none;
}
#logout {
all: initial;
font-family: "Comic Sans MS", "Comic Sans", cursive;
cursor: pointer;
}
#logout:hover{
color: blue;
}
</style>
<script src="script/main.js"></script>
</head>
<body>
<div id="test" class = "topnav">
<a class=active>Home</a>
<a href=news.php>News</a>
<a href=contact.php>Contact</a>
<a href=about.php>About</a>
<a href=buy.php>Buy</a>
<?php
if(isset($_COOKIE['username'])){
echo "<a href=game.php>Play</a>";
echo "<button onclick=" . "document.getElementById('id04').style.display='block'" . ">Profile</button>";
}else{
echo "<button onclick=" . "document.getElementById('id01').style.display='block'" . ">Sign Up</button>";
echo "<button onclick=" . "document.getElementById('id02').style.display='block'" . "> Login</button>";
}
?>
</div>
<div id="id01" class="modal" style = 'padding-top: 50px;'>
<form id=signUpForm class="modal-content">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<div class="container">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<p id ="errusra" class="err"></p>
<label><b>Username</b></label>
<input id="signUpUsername" type="text" placeholder="Enter Username" class = "profile" required>
<p id="erremaila" class="err"></p>
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" id="signUpEmail" class = "profile" required>
<p id="errpswa" class="err"></p>
<label><b>Password</b></label>
<input id="signUpPassword"type="password" placeholder="Enter Password" class = "profile" required>
<p id="errrepswa" class="err"></p>
<label><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" id="passwordRepeat" class = "profile" required>
<label>
<input type="checkbox" checked="checked" style="margin-bottom:15px"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelSignUpbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</div>
<div id="id02" class="modal" style = "padding-top: 50px;">
<form id="loginform"class="modal-content animate">
<div class="imgcontainer">
<span onclick="document.getElementById('id02').style.display='none'" class="close" title="Close Modal">×</span>
<img src="images/loginformimg.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<p id="loginerr" class = 'err'></p>
<label><b>Username</b></label>
<input id="loginUsername"type="text" placeholder="Enter Username" class="profile" required>
<label><b>Password</b></label>
<input id="loginPassword"type="password" placeholder="Enter Password" class = "profile" required>
<label>
<input type="checkbox" checked="checked" name = "cookies"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1; overflow:auto;">
<button type="submit"style="background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;">Login</button>
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelLoginbtn loginButton">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
<div id="id04" class="modal" style = "padding-top: 50px;">
<form id="changeInfoForm"class = "modal-content animate">
<div class="imgcontainer">
<?php
if(isset($_COOKIE['profilepic'])){
echo "<span onclick=" . '"document.getElementById(' . "'id04').style.display='none' " . '" class="close" title="Close Modal">×</span>
<label for="fileToUpload">
<img src="players/'. $_COOKIE['username']. '/' . $_COOKIE['profilepic'] . '" alt="Avatar" class="avatar" id="img">
</label>
<input type="file" name="fileToUpload" id="fileToUpload">';
}else{
echo "<span onclick=" . '"document.getElementById(' . "'id04').style.display='none' " . '" class="close" title="Close Modal">×</span>
<label for="fileToUpload">
<img src="images/loginformimg.png" alt="Avatar" class="avatar">
</label>
<input type="file" name="fileToUpload" id="fileToUpload">';
}
?>
</div>
<div class="container">
<label>
<b>Username:</b> <input id=changeusername class="profile" name="username"value = <?php echo $_COOKIE['username'];?>>
</label>
<br>
<label>
<b>Email:</b> <input id=changeemail class="profile" name="email"value = <?php if(isset($_COOKIE['email'])){ echo $_COOKIE['email']; } ?>>
</label>
<br>
<label>
<b>New Password:</b> <input id="changerepassword"type="password" name="password"class="profile" >
</label>
<br>
<label>
<b>Current Password:</b> <input id=changepassword type="password" name="new-password"class="profile" required>
</label>
<br>
</div>
<div class="container" style="background-color:#f1f1f1; overflow:auto;">
<input type="submit"style="background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;" value="Change Profile Info"name="submit">
<button type="button" onclick="document.getElementById('id04').style.display='none'" class="cancelLoginbtn loginButton">Cancel</button>
<span class="psw"><a id="logout"onclick="logout()">Logout</a></span>
</div>
</form>
</div>
<script src="profile.js"></script>
<?php include 'selectimage.php'?>
<h1>Welcome to MegaLords</h1>
<p>MegaLords is a place where mortals can become gods, and fallen gods can become true gods once more. Becoming a god is a very difficult process, and cannot be explained. Contact me if you wish to become a god.
<h4>Requirements</h4>
<ul>
<li>You must have beaten the game</li>
<li>You must be a mortal or fallen god</li>
<li>You must be weaker than a lower god</li>
<li>You cannot be a mythical creature, but we are looking for mythical creatures</li>
</ul>
<h4>Instructions</h4>
<ol>
<li>Beat the game</li>
<li>The Owner will immediately contact you, if not contact them</li>
<li>The Owner will grant you goddhood</li>
</ol>
</p>
<footer>
<p>Posted by: Electrox</p>
<p>Contact information: QuiMortemKing#gmail.com.</p>
</footer>
</body>
</html>
This is the website
https://omegalords.ga/
This is the js
if(window.location.href == "http://megalords.000webhostapp.com"){
window.location.href = "https://megalords.000webhostapp.com"
}else {
console.log(window.location.href)
}
// Get the modal
var modalLogin = document.getElementById('id02');
var modalSignUp = document.getElementById('id01');
var modalProfile = document.getElementById('id04');
var loginUsername = document.getElementById("loginUsername");
var loginPassword = document.getElementById("loginPassword");
var loginform = document.getElementById("loginform");
var signUpEmail = document.getElementById("signUpEmail");
var signUpUsername = document.getElementById("signUpUsername");
var signUpPassword = document.getElementById("signUpPassword");
var signUpRePassword = document.getElementById("passwordRepeat");
var signUpForm = document.getElementById("signUpForm");
var changeInfoUsername = document.getElementById("changeusername")
var changeInfoEmail = document.getElementById("changeemail")
var changeInfoPassword = document.getElementById("changepassword")
var changeInfoRePassword = document.getElementById("changerepassword")
var changeInfoForm = document.getElementById("changeInfoForm")
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modalLogin) {
modalLogin.style.display = "none";
}else if (event.target == modalSignUp) {
modalSignUp.style.dis4play = "none";
}else if (event.target == modalProfile){
modalProfile.style.display = "none";
}
}
var style = document.createElement('style');
var topnav = document.getElementsByClassName('topnav')[0];
var percent = 1/topnav.childElementCount * 100;
style.innerHTML += ".topnav a, button{float: left; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; BORDER: none; width: " + percent + "%; }"
document.getElementsByTagName('head')[0].appendChild(style);
var getEmail = function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
if(this.responseText == "Please Refresh"){
location.reload();
}else {
return;
}
}else if(this.status == 404 || this.readyState === 0 || this.status == 404 && this.readyState === 0){
document.body.innerHTML = "File Not Found"
}
}
xhttp.open("GET", "getemail.php", true)
xhttp.send()
}
var getProfilepic = function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText == "Please Refresh"){
location.reload();
}else if(this.responseText == "Your Account is Broken. The Dev Has Been Notified"){
document.body.innerHTML += this.responseText
}else if(this.responseText == "No Profile Picture Found"){
var confirmation = confirm("Would You like to Set a Profile picture?");
if(confirmation === true){
modalProfile.style.display = "block"
}
}
}
}
xhttp.open("GET", 'getprofileimage.php', true)
xhttp.send()
}
var signUp = function(event){
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText == " Sign Up Complete"){
location.reload();
}else{
if(this.responseText == "No"){
document.getElementById("errusra").innerHTML = this.responseText;
}else{
switch(this.responseText){
case " *That Username Is Taken":
document.getElementById("errusra").innerHTML = this.responseText;
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *You may only have letters and numbers as a username":
document.getElementById("errusra").innerHTML = this.responseText;
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *You must have between 2 and 8 characters as username":
document.getElementById("errusra").innerHTML = this.responseText;
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *Invalid email":
document.getElementById("erremaila").innerHTML = this.responseText;
document.getElementById("errusra").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *You must have at least one lowercase, uppercase, and a number as a password":
document.getElementById("errpswa").innerHTML = this.responseText;
document.getElementById("errusra").innerHTML = "";
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *You may only have between 3 and 12 characters as password":
document.getElementById("errpswa").innerHTML = this.responseText;
document.getElementById("errusra").innerHTML = "";
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errrepswa").innerHTML = "";
break;
case " *Passwords do not match":
document.getElementById("errrepswa").innerHTML = this.responseText;
document.getElementById("errusra").innerHTML = "";
document.getElementById("erremaila").innerHTML = "";
document.getElementById("errpswa").innerHTML = "";
break;
default:
document.body.innerHTML =this.responseText
console.log(this.responseText)
}
}
}
}
}
xhttp.open("GET",'checkregister.php?eml=' + signUpEmail.value + '&usrnm=' + signUpUsername.value + '&psw=' + signUpPassword.value + '&repsw='+ signUpRePassword.value,true);
xhttp.send();
}
var login = function(event){
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
if(this.responseText == "Login Successful!"){
location.reload();
}else{
modalLogin.style.display = "block";
console.log(this.responseText)
document.getElementById("loginerr").innerHTML = this.responseText;
}
}
}
xhttp.open("GET",'checklogin.php?usrnm=' + loginUsername.value + '&psw=' + loginPassword.value,true)
xhttp.send();
}
var logout = function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
location.reload();
}
}
xhttp.open("GET",'logout.php', true);
xhttp.send();
}
var changeInfo = function(event){
event.preventDefault();
var xhttp = new XMLHttpRequest();
window.wormData = new FormData();
var file = document.getElementById("fileToUpload").files[0];
wormData.append('fileToUpload', file)
wormData.append('username',changeInfoUsername.value);
wormData.append('email',changeInfoEmail.value);
wormData.append('password',changeInfoPassword.value);
if(!(changeInfoRePassword.value == "")){
wormData.append('new-password',changeInfoRePassword.value)
}
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
console.log(this.responseText)
}
}
xhttp.open("POST","changeinfo.php",true);
xhttp.send(wormData);
}
signUpForm.addEventListener('submit',signUp);
loginform.addEventListener('submit',login);
changeInfoForm.addEventListener('submit',changeInfo);
getEmail();
getProfilepic();
This is the php
<?php
include 'templates/connect.php';
if(isset($_POST['username'])){
$username = $_POST['username'];
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
if(isset($_POST['password'])){
$password = $_POST['password'];
}
if(isset($_POST["new-password"])){
$newpassword = $_POST["new-password"];
}
$currusername = $_COOKIE['username'];
$query="SELECT * FROM `Users`
WHERE `username` = '$currusername' AND `psw` = '$password';";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
$id = $row[0];
//echo $row[3];
if(!$result || mysqli_num_rows($result) === 0){
echo $username . $password;
}else{
if($row[1] === $username){
if($row[3] === $email || $email == ""){
if(isset($newpassword)){
$query="UPDATE `Users` SET `psw` = '$newpassword' WHERE `id` = '$id';";
echo $query;
$result = mysqli_query($conn, $query);
}else {
echo "Everything is the same";
}
}
}else if(isset($email)){
if(isset($newpassword)){
$query="UPDATE `Users` SET `username` = '$username' WHERE id = '$id';
UPDATE `Users` SET `password` = '$newpassword' WHERE `id` = '$id';";
rename('players/' . $row[1], 'players/' . $username);
$result = mysqli_query($conn, $query);
}
}else if(isset($newpassword)){
$query="UPDATE `Users` SET `username` = '$username' WHERE id = '$id';
UPDATE `Users` SET `email` = '$email' WHERE id = '$id';
UPDATE `Users` SET `password` = '$newpassword' WHERE `id` = '$id';";
$result = mysqli_query($conn, $query);
rename('players/' . $row[1], 'players/' . $username);
}else {
echo "Everything is the same";
}
}
foreach($_FILES as $data){
echo $data[name];
}
if(isset($_FILES['fileToUpload'])){
$target_dir = "players/". $_COOKIE['username'] . "/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(file_exists($_FILES['fileToUpload']['tmp_name']) || is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo basename( $_FILES["fileToUpload"]["name"]);
$query = "UPDATE `Users` SET `userimage` = '". $_FILES["fileToUpload"]["name"] . "' WHERE `username` = '$currusername'";
unlink("players/$row[1]/$row[5]");
$result = mysqli_query($conn, $query);
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
}
?>
You have to set the enctype attribute in your form, so that the server can read the file.
<form id="changeInfoForm" class = "modal-content animate" enctype="multipart/form-data">
Related
<?php
session_start();
require_once "../connector.php";
$errors = array();
if(isset($_POST["create"])){
$fname = $_POST['fname'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$cpass = $_POST['cpass'];
if($fname == "" || $email == "" || $pass == "" || $cpass == ""){
$errors['fname'] = "Please enter your full name.";
$errors['email'] = "Please enter your email address.";
$errors['pass'] = "Please enter a password.";
$errors['cpass'] = "Please confirm your password.";
header("Location:createaccountform.php");
}else{
$usercheckquery = "SELECT * FROM userdetails WHERE EMAIL_ADDRESS = '$email'";
$result = mysqli_query($conn, $usercheckquery);
if(mysqli_num_rows($result)>0){
$errors['email'] = "This email already exists. Please use another one.";
header("Location:createaccountform.php");
}
else if(!preg_match("/^[a-zA-Z ]*$/",$fname)){
$errors['email'] = "Please enter a valid full name.";
header("Location:createaccountform.php");
}
else if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)){
$errors['email'] = "This email format is invalid.";
header("Location:createaccountform.php");
}
else if(strlen($pass) < 8){
$errors['email'] = "Your password must have a minimum of 8 characters";
header("Location:createaccountform.php");
}
else if($cpass != $pass){
$errors['email'] = "The passwords do not match.";
header("Location:createaccountform.php");
}
else{
$hashedpassword = password_hash($pass, PASSWORD_DEFAULT);
$sql = "INSERT INTO `loginundregistration`.`userdetails`(`FULLNAME`,`EMAIL_ADDRESS`,`USERPASSWORD`)
VALUES ('$fname','$email','$hashedpassword')";
$query = mysqli_query($conn, $sql);
if($query){
//$message = "Created account successfully";
header("Location:createaccountform.php");
}
else{
//$message = "Error creating account. Please try again";
header("Location:createaccountform.php");
}
}
}
}
header('Content-Type: application/json');
echo json_encode($errors);
?>
form.addEventListener("submit", function (e) {
e.preventDefault();
const data = new FormData(form);
const xhttp = new XMLHttpRequest();
xhttp.open("POST", "register.php", true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.onload = function () {
if (this.status === 200) {
let response = JSON.parse(xhttp.responseText);
console.log(response);
for (const key in response) {
const errorID = key + '-error';
const errorMessage = response[key];
const errorSmall = document.getElementById(errorID);
if (errorMessage) {
errorSmall.innerHTML = errorMessage;
errorSmall.classList.remove('success');
errorSmall.classList.add('error');
} else {
errorSmall.innerHTML = '';
errorSmall.classList.remove('error');
errorSmall.classList.add('success');
}
}
}
};
xhttp.send(data);
});
form.addEventListener('click', function (e) {
const target = e.target;
if (target.type === 'text' || target.type === 'email' || target.type === 'password') {
const errorID = target.id + '-error';
const errorSmall = document.getElementById(errorID);
errorSmall.innerHTML = '';
errorSmall.classList.remove('error');
errorSmall.classList.add('success');
}
});
<!DOCTYPE html>
<?php
require_once "../connector.php";
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<!--<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css"/>-->
<script src="https://kit.fontawesome.com/c90e5c3147.js" crossorigin="anonymous"></script>-
<title>Create an Account</title>
</head>
<body>
<div class="container">
<div class="header">
<h2>Create Account</h2>
</div>
<form class="form" action = "register.php" method="POST" id="form" name="form">
<div class="form-control">
<label>Full Name</label>
<input type="text" placeholder="Please enter your full name" id="fname" name="fname">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small id="fname-error"></small>
</div>
<div class="form-control">
<label>Email Address</label>
<input type="email" placeholder="Please enter your email address" id="email" name="email">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small id="email-error"></small>
</div>
<div class="form-control">
<label>Password</label>
<input type="password" placeholder="Please enter a password" id="pass" name="pass">
<i class="fa-solid fa-eye-slash" id="togglePass"></i>
<small id="pass-error"></small>
</div>
<div class="form-control">
<label>Confirm Password</label>
<input type="password" placeholder="Please confirm your password" id="cpass" name="cpass">
<i class="fa-solid fa-eye-slash" id="toggleCPass"></i>
<small id="cpass-error"></small>
</div>
<input type="hidden" value="Create Account" name="create">
<button id="createbtn" name="createbtn">Create Account</button>
</form>
</div>
<script src="js/script.js"></script>
</body>
</html>
.form-control.success input{
border-color: #2ecc71;
}
.form-control.error input{
border-color: #e74c3c;
}
.form-control i{
position: absolute;
top: 40px;
right: 10px;
visibility: hidden;
}
.form-control.success i.fa-check-circle{
color: #2ecc71;
visibility: visible;
}
.form-control.error i.fa-exclamation-circle{
color: #e74c3c;
visibility: visible;
}
.form-control small{
visibility: hidden;
position: absolute;
bottom: 0;
left: 0;
}
.form-control.success small{
color: #2ecc71;
}
.form-control.error small{
color: #e74c3c;
}
The code above is as simple registration form. I wrote some code to take server side PHP validation through AJAX and JSON and show it to the user through error messages on the form. I also added CSS to make the messages look better. The first part of code is the PHP where I store the message in an array called $errors and turn it into JSON string. The next is the JavaScript file where the JSON is parsed using AJAX and the JavaScript adds a class name to the HTML to show the correct CSS properties. The last two parts are the HTML and CSS. it doesn't display anything unfortunately. Even when I console the parsed JSON it is just an empty array. Any clue on why it doesn't work and how to fix it?
The form submission is based on the PHPMailer library (ver. 6.0.7) I would like the form data, such as userName, userPhone and userEmail, to be added to the header of the message. How to add form data in the message body. for example:
userName
userPhone
userEmail
Message content
How should it look like in my example?
PHP
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if(!empty($_POST["send"])) {
require_once ('vendor/autoload.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->Port = 465;
$mail->Username = "**********";
$mail->Password = "**********";
$mail->Mailer = "smtp";
$mail->CharSet = "UTF-8";
if (isset($_POST["userEmail"])) {
$userEmail = $_POST["userEmail"];
}
if (isset($_POST["userName"])) {
$userName = $_POST["userName"];
}
if (isset($_POST["userPhone"])) {
$userPhone = $_POST["userPhone"];
}
if (isset($_POST["subject"])) {
$subject = $_POST["subject"];
}
if (isset($_POST["userMessage"])) {
$message = $_POST["userMessage"];
}
$mail->SetFrom("my email");
$mail->AddReplyTo($userEmail, $userName);
$mail->AddAddress("my email");
$mail->Subject = $subject;
$mail->WordWrap = 80;
$mail->MsgHTML($message);
$mail->IsHTML(true);
$mail->SMTPSecure = 'ssl';
$mail->Host = '**********';
if (! empty($_FILES['attachment'])) {
$count = count($_FILES['attachment']['name']);
if ($count > 0) {
for ($i = 0; $i < $count; $i ++) {
if (! empty($_FILES["attachment"]["name"])) {
$tempFileName = $_FILES["attachment"]["tmp_name"][$i];
$fileName = $_FILES["attachment"]["name"][$i];
$mail->AddAttachment($tempFileName, $fileName);
}
}
}
}
if (! $mail->Send()) {
$message = "Ups :( Error";
$type = "error";
} else {
$message = "Successfull";
$type = "success";
}
}
?>
HTML and JavaScript
<?php
require_once "mail-sending-script.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link href="style.css" rel="stylesheet" type="text/css" />
<title>PHP Contact Form with Add More File Attachment Option</title>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"
type="text/javascript"></script>
<script type="text/javascript">
function validate() {
var valid = true;
$(".info").html("");
var userName = document.forms["mailForm"]["userName"].value;
var userPhone = document.forms["mailForm"]["userPhone"].value;
var userEmail = document.forms["mailForm"]["userEmail"].value;
var subject = document.forms["mailForm"]["subject"].value;
var userMessage = document.forms["mailForm"]["userMessage"].value;
if (userName == "") {
$("#userName-info").html("(required)");
$("#userName").css('background-color', '#FFFFDF');
valid = false;
}
if (userPhone == "") {
$("#userPhone-info").html("(required)");
$("#userPhone").css('background-color', '#FFFFDF');
valid = false;
}
if (userEmail == "") {
$("#userEmail-info").html("(required)");
$("#userEmail").css('background-color', '#FFFFDF');
valid = false;
}
if (!userEmail.match(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/))
{
$("#userEmail-info").html("(invalid)");
$("#userEmail").css('background-color', '#FFFFDF');
valid = false;
}
if (subject == "") {
$("#subject-info").html("(required)");
$("#subject").css('background-color', '#FFFFDF');
valid = false;
}
if (userMessage == "") {
$("#userMessage-info").html("(required)");
$("#userMessage").css('background-color', '#FFFFDF');
valid = false;
}
return valid;
}
function addMoreAttachment() {
$(".attachment-row:last").clone().insertAfter(".attachment-row:last");
$(".attachment-row:last").find("input").val("");
}
</script>
</head>
<body>
<h1>PHP Contact Form with Add More File Attachment Option</h1>
<div class="attachment-form-container">
<form name="mailForm" id="mailForm" method="post" action=""
enctype="multipart/form-data" onsubmit="return validate()">
<div class="input-row">
<label style="padding-top: 20px;">Name</label> <span
id="userName-info" class="info"></span><br /> <input
type="text" class="input-field" name="userName"
id="userName" />
</div>
<div class="input-row">
<label>Telefon</label> <span id="telefon-info"
class="info"></span><br /> <input type="text"
class="input-field" name="telefon" id="telefon" />
</div>
<div class="input-row">
<label>Email</label> <span id="userEmail-info"
class="info"></span><br /> <input type="text"
class="input-field" name="userEmail" id="userEmail" />
</div>
<div class="input-row">
<label>Subject</label> <span id="subject-info"
class="info"></span><br /> <input type="text"
class="input-field" name="subject" id="subject" />
</div>
<div class="input-row">
<label>Message</label> <span id="userMessage-info"
class="info"></span><br />
<textarea name="userMessage" id="userMessage"
class="input-field" id="userMessage" cols="60"
rows="6"></textarea>
</div>
<div class="attachment-row">
<input type="file" class="input-field"
name="attachment[]">
</div>
<div onClick="addMoreAttachment();"
class="icon-add-more-attachemnt"
title="Add More Attachments">
<img src="icon-add-more-attachment.png"
alt="Add More Attachments">
</div>
<div>
<input type="submit" name="send" class="btn-submit"
value="Wyślij" />
<div id="statusMessage">
<?php
if (! empty($message)) {
?>
<p class='<?php echo $type; ?>Message'><?php echo $message; ?></p>
<?php
}
?>
</div>
</div>
</form>
</div>
</body>
</html>
It looks like you've adapted this code from a very old example.
The easiest way to assemble your message body is with a heredoc (note comments in the docs on indenting):
$mail->isHTML(false);
$mail->Body = <<<EOT;
Name: $userName
Phone: $userPhone
Email: $userEmail
Message: $message
EOT;
Since your content is not HTML, there's no point in using msgHTML(); set Body directly, and disable HTML, as this example does.
A separate problem is that your file upload handling code is unsafe. Scrap it and start again using the code in the multiple file upload example provided with PHPMailer.
The following errors occur when submitting the form below:
Syntax error, unexpected '<<'(T_SL)
Syntax error, unexpected (T_STRING)**
My goal is to get the submit action to work. After getting the submit to work I want to add a recaptcha to the form. I have tried the following:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
if(!empty($_POST["send"])) {
require_once ('vendor/autoload.php');
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->Port = 465;
$mail->Username = "********";
$mail->Password = "*******";
$mail->Mailer = "smtp";
$mail->CharSet = "UTF-8";
if (isset($_POST["userEmail"])) {
$userEmail = $_POST["userEmail"];
}
if (isset($_POST["userName"])) {
$userName = $_POST["userName"];
}
if (isset($_POST["userPhone"])) {
$userPhone = $_POST["userPhone"];
}
if (isset($_POST["subject"])) {
$subject = $_POST["subject"];
}
if (isset($_POST["userMessage"])) {
$message = $_POST["userMessage"];
}
$mail->SetFrom("my email");
$mail->AddReplyTo($userEmail, $userName);
$mail->AddAddress("my emaill");
$mail->Subject = $subject;
$mail->WordWrap = 80;
$mail->isHTML(false);
$mail->Body = <<<EOT;
Name: $userName
Phone: $userPhone
Email: $userEmail
Message: $message
EOT;
$mail->SMTPSecure = 'ssl';
$mail->Host = '*********';
for ($ct = 0; $ct < count($_FILES['userfile']['tmp_name']); $ct++) {
$tempFileNamee = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name'][$ct]));
$filename = $_FILES['userfile']['name'][$ct];
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$ct], $tempFileName)) {
$mail->addAttachment($$tempFileName, $filename);
} else {
$$message .= 'Failed to move file to ' . $tempFileNamee;
}
}
if (! $mail->Send()) {
$message = "Ups :( Error";
$type = "error";
} else {
$message = "Successfull";
$type = "success";
}
}
?>
I have a admin panel for login. I have created a login page with php,
html, java script. I used session to pass user to next page. This working perfectly on my localhost. But on live server i am getting problem, its showing me "loged in successfully" popup and redirecting back to login page. When i print session on localhost its showing me session value but on live server its empty. I have searched so many answers and tried same but still it's not working. Please help and thank you for your time and consideration.
My live server is Apache HTTP Server Version 2.2
My connection file db.php is
<?php
/*Default time zone ,to be able to send mail */
date_default_timezone_set('Asia/Kolkata');
//connect database
$con = mysqli_connect ("localhost","rootuser","password","testdbname"); //host, username, password, database name
//database connect error
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: " . mysqli_connect_errno();
}
?>
login.php file is
<?php
session_start();
include("includes/db.php");
if(isset($_SESSION['mysesiuid']))
{
header('Location: index.php?alreadyin');
//echo "<script>window.location.assign('index.php?alreadyin')</script>";
}
else
{
?>
<script src="assets/js/validate/jquery.js" type="text/javascript"></script>
<script>
//login script
$(document).ready(function() {
var mazalagna_login_email1 = 1;
var mazalagna_login_email2 = 1;
var mazalagna_login_email3 = 1;
var mazalagna_login_password = 1;
$("#main_login_submit").click(function(){
//password
if($("#mazalagna_pass").val() == ''){
$("#mazalagna_pass").css("border","1px solid red");
$("#mazalagna_password_error").show();
mazalagna_login_password = 1;
}else{
if($("#mazalagna_pass").val().length < 6){
$("#mazalagna_pass").css("border","1px solid red");
$("#mazalagna_password_length_error_longform").show();
$("#mazalagna_password_error").hide();
mazalagna_login_password = 1;
}else{
$("#mazalagna_pass").css("border","1px solid green");
$("#mazalagna_password_length_error_longform").hide();
$("#mazalagna_password_error").hide();
mazalagna_login_password = 0;
}
}
//email
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
var validateMazalagnaEmail = pattern.test($("#mazalagna_email").val());
if($("#mazalagna_email").val() == ''){
$("#mazalagna_email").css("border","1px solid red");
$("#mazalagna_email_error").show();
mazalagna_login_email1 = 1;
}else{
$("#mazalagna_email").css("border","1px solid green");
$("#mazalagna_email_error").hide();
mazalagna_login_email1 = 0;
}
if(!validateMazalagnaEmail){
$("#mazalagna_email").css("border","1px solid red");
$("#mazalagna_email_error").show();
mazalagna_login_email2 = 1;
}else{
$("#mazalagna_email").css("border","1px solid green");
$("#mazalagna_email_error").hide();
mazalagna_login_email2 = 0;
}
if(validateMazalagnaEmail){
$.ajax({
type: "POST",
cache: false,
url: "php/ajax_email_exist.php",
data: { email: $("#mazalagna_email").val()},
success: function (data)
{
if(data != 1){
$("#mazalagna_email").css("border","1px solid green");
$("#mazalagna_exist_email_error").hide();
mazalagna_login_email3 = 0;
}else{
$("#mazalagna_email").css("border","1px solid red");
$("#mazalagna_exist_email_error").show();
mazalagna_login_email3 = 1;
}
if(mazalagna_login_email1 == 0 && mazalagna_login_email2 == 0 && mazalagna_login_email3 == 0 && mazalagna_login_password == 0 ){
$.ajax({
type: "POST",
cache: false,
url: "main_login.php",
data: {
username1: $("#mazalagna_email").val(),
password1: $("#mazalagna_pass").val()
},
success: function (data)
{
alert(data);
//alert("Welcome! You have loged in successfully!");
window.location.replace("index.php");
}
});
}
}
});
}
//edit value
$(".regval").click(function(){
var id = "#"+$(this).attr("id");
var errorId = "#"+$(this).attr("id")+"_error";
$(id).css("border","1px solid #a39e9e");
$(errorId).hide();
});
});
});
</script>
<strong> Enter Details To Login </strong>
<!-- <form role="form" action="" method="post"> -->
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-tag" ></i></span>
<input type="text" id="mazalagna_email" name="mazalagna_email" class="form-control regval" placeholder="Your Username" required />
</div>
<div id="mazalagna_email_error" style="display:none; margin-top:-12px; margin-bottom:12px; text-align:center; color:red; font-size:12px;">Please enter valid Email</div>
<div id="mazalagna_exist_email_error" style="display:none; margin-top:-12px; margin-bottom:12px; text-align:center; color:red; font-size:12px;">Your email id is not registered.</div>
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-lock" ></i></span>
<input type="password" id="mazalagna_pass" name="mazalagna_pass" class="form-control regval" placeholder="Your Password" required />
</div>
<div id="mazalagna_password_error" style="display:none; margin-top:-12px; margin-bottom:12px; text-align:center; color:red; font-size:12px;">Please enter your password</div>
<div id="mazalagna_password_length_error_longform" style="display:none; margin-top:-12px; margin-bottom:12px; text-align:center; color:red; font-size:12px;">Enter min 6 character password</div>
<button type="submit" id="main_login_submit" name="main_login_submit" class="btn btn-primary ">Login Now</button>
<hr />
<!-- </form> -->
<?php } // top else close here ?>
My main_login.php file is
<?php
//connect database
session_start();
require_once 'includes/db.php';
global $con;
$user_email = trim($_POST['username1']);
$user_password = trim($_POST['password1']);
$password = mysqli_real_escape_string($con, md5($user_password));
$res = $con->query("SELECT * FROM useradmins WHERE email='$user_email' AND password='$password'");
$row = $res->fetch_assoc();
$uid = $row['admin_id'];
$name = $row['name'];
$useremail = $row['email'];
$pass = $row['password'];
if($useremail==$user_email && $pass==$password){
$_SESSION['mysesi']=$name;
$_SESSION['mysesiuid']=$useremail;
echo "Loged in successfully.";
//update status and login time
date_default_timezone_set('Asia/Kolkata');
$date_email = date('F j, Y h:i A');
$date = date('Y-m-d H:i:s');
$user = $_SESSION['mysesiuid'];
$ip = $_SERVER['REMOTE_ADDR'];
$httpref = $_SERVER['HTTP_REFERER'];
$httpagent = $_SERVER['HTTP_USER_AGENT'];
$update_last_login="UPDATE useradmins SET admin_status='ONLINE',active_ip_address='$ip',admin_last_login='$date' WHERE admin_id='$user'";
$update_last_login = mysqli_query($con, $update_last_login);
}
else{
echo "Unable to login.";
}
?>
index.php file is
<?php
session_start();
require_once 'includes/db.php';
if(!isset($_SESSION['mysesiuid']))
{
header('Location: login.php');
exit;
}
else
{
?>
<h1>hi success</h1>
<?php } ?> <!-- top else statement close here -->
hi guys im trying to update user details via ajax but its not updating my users table and just stop executing when possessing... appear here is my code please help if possible
edit_profile.php
<?php
if(isset($_POST["la"])){
$firstname = strip_tags(preg_replace('#[^a-z0-9]#i', '', $_POST['fi']));
$lastname = strip_tags(preg_replace('#[^a-z]#', '', $_POST['la']));
$age = strip_tags(preg_replace('#[0-9]#', '', $_POST['ag']));
$gender = strip_tags(preg_replace('#[^a-z]#', '', $_POST['g']));
// FORM DATA ERROR HANDLING
if($gender == "" || $firsname == "" || $lastname == "" || $age == ""){
echo "some account info is empty.";
exit();
}else{
$sql = "UPDATE users SET gender='$gender', age='$age', lastname='$lastname, firstname='$firstname' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo "account_success";
exit();
}
}
?>
ajax and js
<script type="text/javascript" language="javascript">
function _(x){
return document.getElementById(x);
}
function toggleElement(x){
var x = _(x);
if(x.style.display == 'block'){
x.style.display = 'none';
}else{
x.style.display = 'block';
}
}
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "firstname"){
rx = /[^a-z0-9]/gi;
} else if(elem == "lastname"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function update_profile() {
var fi = _("firstname").value;
var la = _("lastname").value;
var g = _("gender").value;
var ag = _("age").value;
var status2 = _("status_profile");
if(fi == "" || la == "" || ag == "" || g == ""){
status2.innerHTML = "Fill out all of the form data";
status2.style.color = "red";
}else {
_("profilebtn").style.display = "none";
status2.innerHTML = 'processing ...';
var ajax = ajaxObj("POST", "edit_profile.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "account_success"){
_("profilebtn").style.display = "block";
}
}
}
ajax.send("&fi="+fi+"&la="+la+"&g="+g+"&ag="+ag);
}
}
</script>
the html
<div class="row profile-classic">
<div class="col-md-12 m-t-20">
<form name="updateform" id="updateform" onsubmit="return false;">
<div id="profile_form" class="panel">
<div class="panel-title line">
<div class="caption"><i class="fa fa-phone c-gray m-r-10"></i>ACCOUNT</div>
</div>
<div class="panel-body">
<div class="row">
<div class="control-label c-gray col-md-3">Username:</div>
<div class="col-md-6">
<input type="text" class="form-control" value="<?php echo $uname; ?>" disabled="disabled">
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Firstname: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="firstname" contenteditable="true" value="<?php echo $firstname; ?>">
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Lastname: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="lastname" placeholder="your lastname" value="<?php echo $lastname; ?>" >
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Age: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="age" value="<?php echo $age; ?>">
</div>
</div><br />
<div class="row">
<div class="col-md-6">
<select class="form-control" onfocus="emptyElement('status_profile')" id="gender" class="form-control">
<option value="<?php echo $gender; ?>"><?php echo $sex; ?></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
</div>
<button id="profilebtn" onclick="update_profile()" class="btn btn-sm btn-default"><i class="fa fa-floppy-o"></i> Save</button><span id="status_profile"></span>
</div><br />
</div>
</div></form>
</div></div>
You can use mysqli_error($db_conx) to determine what the error is... just have your javascript display it nicely for you.
But also - the variable in your WHERE clause ( $log_username ) is undefined.
I have a contact form that I can't seem to send to my Gmail account. It's different from all the contact forms I've seen because the error message is within the HTML. Nothing happens when the submit button is pressed (no email, no error or success message). Please be gentle for I am somewhat new to PHP. I just need some help please.
The HTML
<div class="contactForm">
<div class="successMessage alert alert-success alert-dismissable" style="display: none">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Thank You! E-mail was sent.
</div>
<div class="errorMessage alert alert-danger alert-dismissable" style="display: none">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Oops! An error occured. Please try again later.
</div>
<form class="liveForm" role="form" action="form/send.php" method="post" data-email-subject="Contact Form" data-show-errors="true" data-hide-form="false">
<fieldset>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Name <span>(Required)</span></label>
<input type="text" required name="field[]" class="form-control">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Email <span>(Required)</span></label>
<input type="email" required name="field[]" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Subject</label>
<input type="text" name="field[]" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Message <span>(Required)</span></label>
<textarea name="field[]" required class="form-control" rows="5"></textarea>
</div>
</div>
</div>
<input type="submit" class="btn btn-primary" value="Send Message">
</fieldset>
</form>
</div>
</div>
The JS
/**
* Contact Form
*/
jQuery(document).ready(function ($) {
"use strict";
$ = jQuery.noConflict();
var debug = false; //show system errors
$('.liveForm').submit(function () {
var $f = $(this);
var showErrors = $f.attr('data-show-errors') == 'true';
var hideForm = $f.attr('data-hide-form') == 'true';
var emailSubject = $f.attr('data-email-subject');
var $submit = $f.find('[type="submit"]');
//prevent double click
if ($submit.hasClass('disabled')) {
return false;
}
$('[name="field[]"]', $f).each(function (key, e) {
var $e = $(e);
var p = $e.parent().find("label").text();
if (p) {
var t = $e.attr('required') ? '[required]' : '[optional]';
var type = $e.attr('type') ? $e.attr('type') : 'unknown';
t = t + '[' + type + ']';
var n = $e.attr('name').replace('[]', '[' + p + ']');
n = n + t;
$e.attr('data-previous-name', $e.attr('name'));
$e.attr('name', n);
}
});
$submit.addClass('disabled');
$f.append('<input class="temp" type="hidden" name="email_subject" value="' + emailSubject + '">');
$.ajax({
url: $f.attr('action'),
method: 'post',
data: $f.serialize(),
dataType: 'json',
success: function (data) {
$('span.error', $f).remove();
$('.error', $f).removeClass('error');
$('.form-group', $f).removeClass('has-error');
if (data.errors) {
$.each(data.errors, function (i, k) {
var input = $('[name^="' + i + '"]', $f).addClass('error');
if (showErrors) {
input.after('<span class="error help-block">' + k + '</span>');
}
if (input.parent('.form-group')) {
input.parent('.form-group').addClass('has-error');
}
});
} else {
var item = data.success ? '.successMessage' : '.errorMessage';
if (hideForm) {
$f.fadeOut(function () {
$f.parent().find(item).show();
});
} else {
$f.parent().find(item).fadeIn();
$f[0].reset();
}
}
$submit.removeClass('disabled');
cleanupForm($f);
},
error: function (data) {
if (debug) {
alert(data.responseText);
}
$submit.removeClass('disabled');
cleanupForm($f);
}
});
return false;
});
function cleanupForm($f) {
$f.find('.temp').remove();
$f.find('[data-previous-name]').each(function () {
var $e = jQuery(this);
$e.attr('name', $e.attr('data-previous-name'));
$e.removeAttr('data-previous-name');
});
}
});
The PHP
<?php
// Contact subject
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Enter your email address
$to ='divagraphicsinc#gmail.com';
$send_contact=mail($to,$subject,$message,$header);
?>
<?php
$ajax = (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
$ajax = true;
//we do not allow direct script access
if (!$ajax) {
//redirect to contact form
echo "Please enable Javascript";
exit;
}
require_once "config.php";
//we set up subject
$mail->Subject = isset($_REQUEST['email_subject']) ? $_REQUEST['email_subject'] : "Message from site";
//let's validate and return errors if required
$data = $mail->validateDynamic(array('required_error' => $requiredMessage, 'email_error' => $invalidEmail), $_REQUEST);
if ($data['errors']) {
echo json_encode(array('errors' => $data['errors']));
exit;
}
$html = '<div style="width: 640px; font-size: 11px;">
<h2>' . $mail->Subject . '</h2><ul>
';
foreach ($data['fields'] as $label => $val) {
$html .= '<li>' . $label . ': ' . $val . '</li>';
}
$html .= '</ul></div>';
$mail->setup($html, $_REQUEST, array());
$result = array('success' => 1);
if (!$mail->Send()) {
$result['success'] = 0;
}
echo json_encode($result);
exit;