I'm doing contact form on my portfolio website. I made working PHP form and also working javascript validation but when I tried to add both to work one after another it crash.
To sumarize I would like to know how to call contactForm.php after the all inputs are valid.
Here is my JS code:
function formValidator(){
const form = document.getElementById('form');
const name = document.getElementById('name');
const email = document.getElementById('email');
const message = document.getElementById('message');
let errorStatus = true;
form.addEventListener('submit',(e) => {
e.preventDefault(); // here I stop submiting
checkInputs(); // here I check validation of inputs
if(errorStatus == true){ //if its ok I run this
console.log("Its ok")
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("result").innerHTML = xhttp.responseText;}
};
xhttp.open("POST", "contactForm.php", true);
xhttp.send();
}
else{
form.scrollIntoView({ behavior: 'smooth'});
}
});
function checkInputs(){
const nameValue = name.value.trim();
const emailValue = email.value.trim();
const messageValue = message.value.trim();
if(nameValue === ''){
setErrorFor(name, "Proszę podać imię");
} else{
setSuccessFor(name);
}
}
function setErrorFor(input, message){
const formControl = input.parentElement;
const errorContent = formControl.querySelector('.error-message');
const alertVisibility = formControl.querySelector('.alert');
errorContent.innerText = message;
alertVisibility.style.visibility = "visible";
errorStatus = false;
}
function setSuccessFor(input){
const formControl = input.parentElement;
const alertVisibility = formControl.querySelector('.alert');
alertVisibility.style.visibility = "hidden";
errorStatus = true;
}
}
I added this code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("result").innerHTML = xhttp.responseText;}
};
xhttp.open("POST", "contactForm.php", true);
xhttp.send();
Here is contactForm.php
<?php
// Get data from form
$name = $_POST['name'];
$email= $_POST['email'];
$message= $_POST['message'];
$to = "piotr.brze95#gmail.com";
$subject = "Nowe zlecenie od " . $name . " z strony MelonStudio";
// The following text will be sent
// Name = user entered name
// Email = user entered email
// Message = user entered message
$txt ="Name = ". $name . "\r\n Email = "
. $email . "\r\n Message =" . $message;
$headers = "From: noreply#demosite.com";
if($email != NULL) {
mail($to, $subject, $txt, $headers);
}
?>
and it doesnt work. I also made some research to find the best way to aproach forms and this is what I ended with. PHP form with JS Validation but I can't combine them.
You can also check this website here: My Portfolio and the contact form is in the end of the page.
Update 29.12
After some code updating I managed to send email correctly.
Here is my JS code that check if there is no error and fetching php file:
e.preventDefault();
checkInputs();
if(errorStatus === true){
console.log("Its ok");
phpFetcher();
window.location.href = "https://melon.studio/success-page.html";
} else{
form.scrollIntoView({ behavior: 'smooth'});
}
});
function phpFetcher(){
form.addEventListener('click', function(event){
const formattedFormData = new FormData(form);
postData(formattedFormData);
});
async function postData(formattedFormData){
const response = await fetch('contactForm.php',{
method: 'POST',
body: formattedFormData
});
}
The problem is that JS doesn't wait for executing the php file and redirecting the website instantly.
header("Location:index.html");. this is the first issue. You should remove it. The second issue is you didn't send response for ajax call. You should send response for ajax request by echo "Your message has been sent". In your case, you can return the result of mail function.Please add this code in contactForm.php.
if(mail($to, $subject, $txt, $headers)) {
echo "Your message has been sent";
} else {
echo "Enter the valid email address"
}
Related
Hello, I've recently been building a contact page for my html website and it seems to not send my message to my email at all!
It continues with ->
I am a little confused also why its not sending the message, and the default errors don't pop up with saying "this is required to be filled".
Here is my PHP code (sending the message) :
<?php
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$phone = htmlspecialchars($_POST['phone']);
$website = htmlspecialchars($_POST['website']);
$message = htmlspecialchars($_POST['message']);
if(!empty($email) && !empty($message)){
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$receiver = "MYEMAILHERE";
$subject = "From: $name <$email>";
$body = "Name: $name\nEmail: $email\nPhone: $phone\nWebsite: $website\n\nMessage:\n$message\n\nRegards,\n$name";
$sender = "From: $email";
if(mail($receiver, $subject, $body, $sender)){
echo "Your message has been sent";
}else{
echo "Sorry, failed to send your message!";
}
}else{
echo "Enter a valid email address!";
}
}else{
echo "Email and message field is required!";
}
?>
Here is my JS code (creating the message) :
const form = document.querySelector("form"),
statusTxt = form.querySelector(".button-area span");
form.onsubmit = (e)=>{
e.preventDefault();
statusTxt.style.color = "#0D6EFD";
statusTxt.style.display = "block";
statusTxt.innerText = "Sending your message...";
form.classList.add("disabled");
let xhr = new XMLHttpRequest();
xhr.open("POST", "src/php/message.php", true);
xhr.onload = ()=>{
if(xhr.readyState == 4 && xhr.status == 200){
let response = xhr.response;
if(response.indexOf("required") != -1 || response.indexOf("valid") != -1 || response.indexOf("failed") != -1){
statusTxt.style.color = "red";
}else{
form.reset();
setTimeout(()=>{
statusTxt.style.display = "none";
}, 3000);
}
statusTxt.innerText = response;
form.classList.remove("disabled");
}
}
let formData = new FormData(form);
xhr.send(formData);
}
Here is my HTML code before end of my body (linking the js) :
<script src="src/js/contact.js"></script>
Is there anything i'm missing? Could it be not linking correctly? Im also sending this using an online website, not locally.
Using Githubpages, which does not support PHP. That is the problem.
I am having problems creating a PHP session following a successful AJAX call. Here is the AJAX code:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var em = profile.getEmail();
var name = profile.getName();
var pic = profile.getImageUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('confirm-login').style.display = 'block';
}
};
xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
xhttp.send();
}
This part works perfectly. I only include it for completeness sake.
Here's the contents of profile.php
<?php
$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];
require_once("db.php");
$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");
if($result->num_rows == 0) {
$sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
if (mysqli_query($mysqli, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}
} else {
echo "already exists";
}
$mysqli->close();
session_start();
$_SESSION['gid'] = $id;
?>
All of this code works except for session_start(); and $_SESSION['gid'] = $id; when I return to another PHP page (which correctly has session_start(); at the very top of the page) the variable has not been created in profile.php
Any help as to what I'm doing wrong would be much appreicated.
You can't start a session after the script has sent output. (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed.
On an unrelated topic, you will want to learn how to escape your database parameters.
I have a Question. Instead of having the record insert rather once, It inserts twice into the DB table. I am using a Javascript function to send the Data to a PHP , Now it saves the data to a Database, No doubt , but rather than have one Record, It saves twice. And i do not have a reason as to why this is so.
My javascript used to save data looks like this :
function submitFormData(){
var xhr = new XMLHttpRequest();
var url = 'submit_request.php';
var fullname = document.getElementById("fullname").value;
var address = document.getElementById("address").value;
var address2 = document.getElementById("address2").value;
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
var telephone = document.getElementById("telephone").value;
var email = document.getElementById("email").value;
var vehicle_type = document.getElementById("vehicle_type").value;
var vehicleNo = document.getElementById("vehicleNo").value;
var visit_date = document.getElementById("visit_date").value;
var visit_purpose = document.getElementById("visit_purpose").value;
var whom_tosee = document.getElementById("whom_tosee").value;
var login_time = document.getElementById("login_time").value;
var params = 'fullname='+fullname+'&address='+address+'&address2='+address2+'&city='+city+'&state='+state+'&telephone='+telephone+'&email='+email+'&vehicle_type='+vehicle_type+'&vehicleNo='+vehicleNo+'&visit_date='+visit_date+'&visit_date='+visit_date+'&visit_purpose='+visit_purpose+'&whom_tosee='+whom_tosee+'&login_time='+login_time+'';
var txt = 'Please confirm the following Information\n FullName : '+fullname+'\n Address : '+address+'\n Address2 : '+address2+'\n City: '+city+'\n State: '+state+'\n Telephone: '+telephone+'\n Email: '+email+'\n Vehicle Type: '+vehicle_type+'\n Vehicle #: '+vehicleNo+'\n Visit Date: '+visit_date+'\n Visit Purpose : '+visit_purpose+'\n Who To see : '+whom_tosee+'\n Login Time : '+login_time+'';
var response = confirm(txt);
if(response == true){
xhr.open('GET', url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200) {
// alert('Sending Data');
var finalurl = url +'?'+params;
window.location = finalurl;
}
}
xhr.send(params);
}else{
window.location ='e-vmsreserve.php';
}
}
And the PHP used to save the Data into the DB looks like this
<?php
session_start();
if(!isset($_SESSION['userID']))
{
header("location: index.php");
}
?>
<?php
require_once('inc/config.php');
$con = mysqli_connect($host,$user,$pass,$db) or die ('Cannot connect: '.mysqli_error());
$query = "SELECT * FROM evmsdbusers WHERE username = '".$_SESSION['userID']."'";
$result = mysqli_query($con,$query) or die('Bad Query: '.mysqli_error($con));
while($row = mysqli_fetch_array($result)){
$fullname = $row['fullname'];
$username = $row['username'];
$designation = $row['designation'];
}
?>
<?php
require_once('inc/config.php');
$con = mysqli_connect($host, $user, $pass, $db) or die('Cannot connect, Reason:'.mysqli_error());
$fullname = mysqli_real_escape_string($con,$_GET['fullname']);
$address = mysqli_real_escape_string($con,$_GET['address']);
$address2 = mysqli_real_escape_string($con,$_GET['address2']);
$city = mysqli_real_escape_string($con,$_GET['city']);
$state = mysqli_real_escape_string($con,$_GET['state']);
$telephone = mysqli_real_escape_string($con,$_GET['telephone']);
$email = mysqli_real_escape_string($con,$_GET['email']);
$vehicle_type = mysqli_real_escape_string($con,$_GET['vehicle_type']);
$vehicleNo = mysqli_real_escape_string($con,$_GET['vehicleNo']);
$visit_date = mysqli_real_escape_string($con,$_GET['visit_date']);
$visit_purpose = mysqli_real_escape_string($con,$_GET['visit_purpose']);
$whom_tosee = mysqli_real_escape_string($con,$_GET['whom_tosee']);
$login_time = mysqli_real_escape_string($con,$_GET['login_time']);
$invitee_username =$username;
$sql = "insert into new_reservation (fullname,address,address2,city,state,telephone,email,vehicle_type,vehicleNo,visit_date,visit_purpose,whom_tosee,login_time,visitor_username) values ('".$fullname."','".$address."','".$address2."','".$city."','".$state."','".$telephone."','".$email."','".$vehicle_type."','".$vehicleNo."','".$visit_date."','".$visit_purpose."','".$whom_tosee."','".$login_time."','".$invitee_username."')";
mysqli_query($con, $sql) or die ('Bad Query, Reason: '.mysqli_error($con));
$message = "Appointment Reserved!";
echo '<script type="text/javascript">';
echo 'alert("'.$message.'");';
echo '</script>';
?>
Now what i do not seem to understand is why I am having 2 records,Though not duplicate but it should have only one record.
First of all, your code is wide open for SQL injection, using $_GET is open invitation for SQL injection. I suggest you to use Prepared statement, this will prevent your code for SQL attack.
Issue in your code is window.location = finalurl; this line, this will redirect to same php file with same params, and your query will insert twice due to $_GET values.
So, you just need to show your response when you got response 200, no need to redirect on same url 'submit_request.php' with same params.
Some useful links:
Are PDO prepared statements sufficient to prevent SQL injection?
Prepared Statement Manaul
One more suggestion always exit(); after header(); otherwise your code will not terminate.
php - Should I call exit() after calling Location: header?
Thank You DevPro, Somehow I managed to see where the error was. when performing a get request, it should be in the pattern url+'?'+parameters
I remembered that and tried it in my code, somehow it saves fine now and no Duplicate records or double insert. In case someone needs it in future :), PHP Remains the same.
I did it like this xhr.open('GET', url+"?"+params, true);
function submitFormData(){
var xhr = new XMLHttpRequest();
var url = 'submit_request.php';
var fullname = document.getElementById("fullname").value;
var address = document.getElementById("address").value;
var address2 = document.getElementById("address2").value;
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
var telephone = document.getElementById("telephone").value;
var email = document.getElementById("email").value;
var vehicle_type = document.getElementById("vehicle_type").value;
var vehicleNo = document.getElementById("vehicleNo").value;
var visit_date = document.getElementById("visit_date").value;
var visit_purpose = document.getElementById("visit_purpose").value;
var whom_tosee = document.getElementById("whom_tosee").value;
var login_time = document.getElementById("login_time").value;
var params = 'fullname='+fullname+'&address='+address+'&address2='+address2+'&city='+city+'&state='+state+'&telephone='+telephone+'&email='+email+'&vehicle_type='+vehicle_type+'&vehicleNo='+vehicleNo+'&visit_date='+visit_date+'&visit_date='+visit_date+'&visit_purpose='+visit_purpose+'&whom_tosee='+whom_tosee+'&login_time='+login_time+'';
var txt = 'Please confirm the following Information\n FullName : '+fullname+'\n Address : '+address+'\n Address2 : '+address2+'\n City: '+city+'\n State: '+state+'\n Telephone: '+telephone+'\n Email: '+email+'\n Vehicle Type: '+vehicle_type+'\n Vehicle #: '+vehicleNo+'\n Visit Date: '+visit_date+'\n Visit Purpose : '+visit_purpose+'\n Who To see : '+whom_tosee+'\n Login Time : '+login_time+'';
var response = confirm(txt);
if(response ==true){
xhr.open('GET', url+"?"+params, true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200) {
alert('ok');
}
}
xhr.send(null);
}
}
Thanks everyone!
I am trying to pass data back to the server and then use the reply to update the browser page.
My code for a SELECT input is as follows;
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)"
<?php
$MC = $_SESSION["MatchCapt"];
player_load($MC);
?>
>
</select>
The script code is as follows;
<script>
function findTeleNo(that){
alert("I am an alert box!" + that);
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("TeleNo").value = this.responseText;
}
}
};
xhttp.open("GET", "findTeleNo.php?q=" + that, true);
xhttp.send();
</script>
The purpose of the script is to take the value selected in the dropdown (variable "that") and submit it to the php file as variable q.
And the PHP file is as follows;
<?php
$MatchCaptain = $_REQUEST["q"];
$teleNo = "";
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementDB";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM `playerstb` ORDER BY `Surname` ASC, `FirstName` ASC";
$result = mysqli_query($db_handle, $SQL);
$ufullName = split_name($MatchCaptain);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['FirstName'];
$uName = trim($uName);
$Surname = $db_field['Surname'];
$Surname = trim($Surname);
$fullName = $uName." ".$Surname;
if ($fullName == $ufullName )
{
$teleNo = $db_field['TeleNo'];
break;
}
}
}
echo $teleNo;
function split_name($name) {
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
$ufullName = $first_name." ".$last_name;
return $ufullName;
}
?>
The php file requests the q variable from the url and makes it $MatchCaptain.
This will be a name like Joe Bloggs. The next piece of code connects to a MySQL table to extract players first names surnames and telephone numbers. The first names and surnames are concatenated to form the fullname which is compared with the $MatchCaptainWhen a match is made the variable $teleNo is set to the Telephone Number of that player. The echo statement rerurns the value to the script.
The field id I am trying to update is;
<p><b>Telephone Number: </b> <span id="TeleNo"> <?php echo $_SESSION["TeleNo"]; ?></span></p>
The alert in the script function findTeleNo shows me that I have entered the function but nothing happens after that.
Any help as to how I get this working would be grateful.
I have changed my script to
<script>
function findTeleNo(that){
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "findTeleNo.php?q=" + encodeURIComponent(that), true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
// OK
alert('response:'+xhttp.responseText);
document.getElementById("TeleNo").innerHTML = this.responseText;
// here you can use the result (cli.responseText)
} else {
// not OK
alert('failure!');
}
}
};
};
</script>
The response shown by alert('response:'+xhttp.responseText); is correct and the line of code
document.getElementById("TeleNo").innerHTML = this.responseText;
does print the response to the web page.
I am using the jQuery Form Post plugin from malsup, with the following code:
//Post a form
function PostForm(FormID, Target) {
var $t = Math.round(new Date().getTime() / 1000);
try{
var options = {
target: Target,
beforeSubmit: function () {
jQuery(Target).html('<div id="frmLoadingImageWrapper"><img src="/assets/images/ajax-loader.gif" alt="loading..." height="11" width="16" /></div>');
jQuery(Target).slideDown('slow');
},
success: function (html) {
setTimeout(function () {
jQuery(Target).html(html);
jQuery(FormID)[0].reset();
if($('#captcha-gen').length){
$.get('/inc/captcha.php?_=' + $t, function(data){
$('#captcha-gen').html(data);
});
}
}, 100);
},
error: function(e){
var $html = e.responseText;
jQuery(Target).html($html);
jQuery(Target).slideDown('fast');
if($('#captcha-gen').length){
$.get('/inc/captcha.php?_=' + $t, function(data){
$('#captcha-gen').html(data);
});
}
setTimeout(function() {
jQuery(Target).slideUp('fast');
}, 3500);
}
};
jQuery(FormID).ajaxSubmit(options);
}catch(err){
alert(err.message);
}
}
When I submit my form to /inc/mail.php the actuall PHP code shows in my Target instead of getting processed.
How can I fix this issue? All other PHP scripts work as they should, including other ajax pulled php scripts.
Here is the mailer code, it's using PHP SMTP
<?
require("/inc/class.phpmailer.php");
//form validation vars
$formok = true;
$errors = array();
//sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('m/d/Y');
$time = date('H:i:s');
//form data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$captcha = $_POST['secAnswer'];
$valid = true;
if(!is_string($email) || !(strlen($email)>0) || !ValidateEmail($email)){
$valid = false;
}
if(!is_string($name) || !(strlen($name)>0) || !ValidateText($name)){
$valid = false;
}
if(!is_string($message) || !(strlen($message)>0) || !ValidateText($message)){
$valid = false;
}
if(!CheckCAPTCHA($captcha)){
$valid = false;
}
sleep(1.5);
if($valid){
$mail = new PHPMailer();
$mail->IsMail(); // send via SMTP
$mail->From = $email; // SMTP username again
$mail->AddAddress("kevin#pirnie.us"); // Your Adress
$mail->Subject = "New mail your site!";
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Body = "<p>You have recieved a new message from the enquiries form on your website.</p>
<p><strong>Name: </strong> {$name} </p>
<p><strong>Email Address: </strong> {$email} </p>
<p><strong>Phone: </strong> {$phone} </p>
<p><strong>Message: </strong> {$message} </p>
<p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";
if(!$mail->Send())
{
echo "Mail Not Sent <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Mail Sent";
}else{
echo "Mail Not Sent. Please make sure all fields are filled out correctly.";
}
function ValidateEmail($str){
$atIndex = strrpos($str, "#");
if (is_bool($atIndex) && !$atIndex){
return false;
}else{
if (filter_var($str, FILTER_VALIDATE_EMAIL)) {
$domain = substr($str, $atIndex + 1);
return (checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"));
}else{
return false;
}
}
}
function ValidateText($str){
return (bool)preg_match("/^[a-zA-Z0-9 _-]+$/", $str);
}
function CheckCAPTCHA($str){
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/captcha.class.php');
$csc = new ResponsiveCaptcha();
if($csc->checkAnswer($str)){
return TRUE;
}else{
return FALSE;
}
}
Make sure that your server supports the short PHP open tag <?
If not : change the short_open_tag value in your php.ini file
or use <?php