Noob PHP Form is not working

I cannot for the life of me get my form to run. I am a recent graduate from college in Web and any help would be greatly appreciated! The form has a name, email, phone, datePicker and message component.

I have been at this for hours now and can’t figure it out.

My HTML aspect of the form:


***Note: Adjusted < & > so you can see code below.

<form id="contact-form">
  <div class="row">
    <div class="col-md-6">
      <input name="name" id="name" type="text" placeholder="Name">
    </div>
    <div class="col-md-6">
      <input name="mail" id="mail" type="text" placeholder="Email">
    </div>
  </div>
  <div class="row">
    <div class="col-md-6">
      <input name="Phone" id="phone" type="text" placeholder="Phone">
    </div>
    <div class="col-md-6">
      <font color="#999999">Date of Preferred Appointment: <input name="Date of Appointment" id="date" type="date" placeholder="Date"></font>
    </div><br>
    </div>
    <textarea name="comment" id="comment" placeholder="Message"></textarea>
    <div class="submit-area">
      <input type="submit" id="submit_contact" value="Send Message">
      <div id="msg" class="message"></div>								
    </div>
</form>

My PHP file:


<?php 

	/* ==========================  Define variables ========================== */

	#Your e-mail address
	define("__TO__", "johndoe@gmail.com");

	#Message subject
	define("__SUBJECT__", "Website.com = From:");

	#Success message
	define('__SUCCESS_MESSAGE__', "Your message has been sent. Thank you!");

	#Error message 
	define('__ERROR_MESSAGE__', "Error, your message hasn't been sent.");

	#Messege when one or more fields are empty
	define('__MESSAGE_EMPTY_FILDS__', "Please fill out all fields.");

	/* ========================  End Define variables ======================== */

	//Send mail function
	function send_mail($to,$subject,$message,$headers){
		if(@mail($to,$subject,$message,$headers)){
			echo json_encode(array('info' => 'success', 'msg' => __SUCCESS_MESSAGE__));
		} else {
			echo json_encode(array('info' => 'error', 'msg' => __ERROR_MESSAGE__));
		}
	}

	//Check e-mail validation
	function check_email($email){
		if(!@eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
			return false;
		} else {
			return true;
		}
	}

	//Get post data
	if(isset($_POST['name']) and isset($_POST['phone']) and isset($_POST['date']) and isset($_POST['mail']) and isset($_POST['comment'])){
		$name 	 = $_POST['name'];
				$phone 	 = $_POST['phone'];
				$date 	 = $_POST['date'];
		$mail 	 = $_POST['mail'];
		$website  = $_POST['website'];
		$comment = $_POST['comment'];

		if($name == '') {
			echo json_encode(array('info' => 'error', 'msg' => "Please enter your name."));
			exit();
			} else if($phone == ''){
			echo json_encode(array('info' => 'error', 'msg' => "Please enter valid phone number."));
			exit();
			} else if($date == ''){
			echo json_encode(array('info' => 'error', 'msg' => "Please enter valid date for perferred appointment."));
			exit();
		} else if($mail == '' or check_email($mail) == false){
			echo json_encode(array('info' => 'error', 'msg' => "Please enter valid e-mail."));
			exit();
		} else if($comment == ''){
			echo json_encode(array('info' => 'error', 'msg' => "Please enter your message."));
			exit();
		} else {
			//Send Mail
			$to = __TO__;
			$subject = __SUBJECT__ . ' ' . $name;
			$message = '
			<html>
			<head>
			  <title>Mail from '. $name .'</title>
			</head>
			<body>
			  <table style="width: 500px; font-family: arial; font-size: 14px;" border="1">
				<tr style="height: 32px;">
				  <th align="right" style="width:150px; padding-right:5px;">Name:</th>
				  <td align="left" style="padding-left:5px; line-height: 20px;">'. $name .'</td>
				</tr>
								<tr style="height: 32px;">
				  <th align="right" style="width:150px; padding-right:5px;">Phone Number:</th>
				  <td align="left" style="padding-left:5px; line-height: 20px;">'. $phone .'</td>
				</tr>
								<tr style="height: 32px;">
				  <th align="right" style="width:150px; padding-right:5px;">Preferred Appointment Date:</th>
				  <td align="left" style="padding-left:5px; line-height: 20px;">'. $date .'</td>
				</tr>
				<tr style="height: 32px;">
				  <th align="right" style="width:150px; padding-right:5px;">E-mail:</th>
				  <td align="left" style="padding-left:5px; line-height: 20px;">'. $mail .'</td>
				</tr>
				<tr style="height: 32px;">
				  <th align="right" style="width:150px; padding-right:5px;">Website:</th>
				  <td align="left" style="padding-left:5px; line-height: 20px;">'. $website .'</td>
				</tr>
				<tr style="height: 32px;">
				  <th align="right" style="width:150px; padding-right:5px;">Comment:</th>
				  <td align="left" style="padding-left:5px; line-height: 20px;">'. $comment .'</td>
				</tr>
			  </table>
			</body>
			</html>
			';

			$headers  = 'MIME-Version: 1.0' . "\r\n";
			$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
			$headers .= 'From: ' . $mail . "\r\n";

			send_mail($to,$subject,$message,$headers);
		}
	} else {
		echo json_encode(array('info' => 'error', 'msg' => __MESSAGE_EMPTY_FILDS__));
	}
 ?>

I may come out as being rude, but shouldn’t a college graduate who majors in web development supposed to know how to create a web form? I am astonished if the school you go to doesn’t supply you with information on how to properly write a web application. What would be more astonishing is wasting tons of money on learning web application when you can’t even apply it to a real life situation.

Anyways, just looking at your snippet, it looks to be written in a terrible manner. The default mail function is not a reliable source to send emails because this function may or may not send emails at times. Even if you had it configured to work, it will most likely fail at very random times.

Another thing to note, you are using deprecated HTML tags. The font tags are obsolete and aren’t used anymore. Just using this website to validate your HTML already tells me something.

1 Like

I’m more on the graphics side utilizing Photoshop and Illustrator but trying my best to get a form up and running. Not rude and a fair question, but I generally wasn’t code focused in instruction.

Alright then. The first thing I would suggest is properly writing the HTML part first. Once you get the HTML part properly written, you can then focus on the PHP part. The HTML part is more important then the PHP part because the HTML part is the presentation where your users can view and see. If you are writing really sloppy HTML, the people who will visit your website will think the person who wrote that page doesn’t really care much about their job at all.

That’s why, the HTML part is more important then having your PHP code working.

Hi WhammyJ

Sorry but “not working” and “can’t run” doesn’t tell me enough.

Does the form display at all?
Does it “work” but gives an error message?
Does it appear to work, but no emails are received?

1 Like
<form id="contact-form">

No “method” or “action” attributes, how will it know what script to load when you click the submit button?

(ETA - maybe it’s submitted by Ajax, given the way the PHP returns error messages. That bit isn’t shown).

There’s a disparity between the field names in your form as defined in the html code, and the field names you validate and use in the PHP code.

2 Likes

To display and format code in the forums you need three backticks on a line of their own before and after the code block.

// some code here

Or highlight the block, then use the </> button on the toolbar.

2 Likes

Fixed… :blush:

3 Likes

You are all rockstars for giving me some help! It is really appreciated. I had some questions today as to if I was a developer why wouldn’t I know how to build a form and just wanted to state for clarification purposes, I am graphic based (Illustrator/Photoshop) so the code end of sites surely is not my forte but I am doing what I can!

After finding out essentially what I have built is quite dated, I followed a tutorial and successfully built a new form utilizing bootstrap from this tutorial (https://webdesign.tutsplus.com/tutorials/building-a-bootstrap-contact-form-using-php-and-ajax--cms-23068). I however, added two additional fields (phone and date (datePicker field)) and while everything runs properly, my print out on my email reads as below. Any ideas on how to correct the print out to display all information correctly? Email shows date and phone and date are left blank currently.

Name: Jeff George
Email: 2017-07-31
Phone:
Date Preferred for Appointment:
Message: Last

My PHP for the above:

$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Phone: ";
$Body .= $phone;
$Body .= "\n";
$Body .= "Date Preferred for Appointment: ";
$Body .= $date;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";

My js statement for the above as well:

    $.ajax({
        type: "POST",
        url: "php/form-process.php",
        data: "name=" + name + "&email=" + email + "&phone=" + phone + "&date=" + date + "&message=" + message,
        success : function(text){
            if (text == "success"){
                formSuccess();
            } else {
                formError();
                submitMSG(false,text);
            }
        }
    });
2 Likes

When you post code, it is much easier for people to read if you format it properly first (see @SamA74’s post above). I did it this time for you, but try to remember next time. :slight_smile:

1 Like

Can you show the bit of JS where you retrieve the form variables before your Ajax call?

I guess that’s the confusion - I’d have called that a web designer, rather than a web developer. I can’t do the design part to save my life.

1 Like

Fair enough! We both speak different languages and I’m trying to use google translate :slight_smile:

Here is my js file in full


$("#contactForm").validator().on("submit", function (event) {
    if (event.isDefaultPrevented()) {
        // handle the invalid form...
        formError();
        submitMSG(false, "Please correct highlighted fields prior to submitting.");
    } else {
        // everything looks good!
        event.preventDefault();
        submitForm();
    }
});
function submitForm(){
    // Initiate Variables With Form Content
    var name = $("#name").val();
    var email = $("#email").val();
	var phone = $("#phone").val();
	var date = $("#date").val();
    var message = $("#message").val();
    $.ajax({
        type: "POST",
        url: "php/form-process.php",
        data: "name=" + name + "&email=" + email + "&phone=" + phone + "&date=" + date + "&message=" + message,
        success : function(text){
            if (text == "success"){
                formSuccess();
            } else {
                formError();
                submitMSG(false,text);
            }
        }
    });
}
function formSuccess(){
    $("#contactForm")[0].reset();
    submitMSG(true, "Message Submitted. We will be in touch with you shortly.")
}
function formError(){
    $("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
        $(this).removeClass();
    });
}
function submitMSG(valid, msg){
    if(valid){
        var msgClasses = "h5 text-center tada animated text-success";
    } else {
        var msgClasses = "h5 text-center text-danger";
    }
    $("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}

Right, well, my original comment about different names still stands, but for different reasons. Look at the form, in particular the ids you have assigned to each field:

<input name="name" id="name" type="text" placeholder="Name">
<input name="mail" id="mail" type="text" placeholder="Email">
<input name="Phone" id="phone" type="text" placeholder="Phone">
<input name="Date of Appointment" id="date" type="date" placeholder="Date">
<textarea name="comment" id="comment" placeholder="Message"></textarea>

and then compare that with the ids you are using to retrieve the data:

var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
var date = $("#date").val();
var message = $("#message").val();

I’m still not entirely sure why you get exactly what you do in the email, but you can see from the above why you don’t get an email address or the message text.

Oh, and then there’s the difference between how you pass the data into the PHP code:

data: "name=" + name + "&email=" + email + "&phone=" + phone + "&date=" + date + "&message=" + message,

and how your PHP code retrieves that data:

$name  = $_POST['name'];
$phone = $_POST['phone'];
$date = $_POST['date'];
$mail = $_POST['mail'];
$website = $_POST['website'];
$comment = $_POST['comment'];

which actually won’t matter because the previous line:

if(isset($_POST['name']) and isset($_POST['phone']) and isset($_POST['date']) and isset($_POST['mail']) and isset($_POST['comment'])){

is checking for the existing of a variable that your Ajax call doesn’t pass into the PHP as part of it’s data, so the stuff inside the if() will never execute. So I’m surprised you get an email at all.

To change this into something slightly more helpful, this input field:

<input type="text" name="lastname" id="surname" size="20">

is accessed in your JS code by

var name = $('#surname').val();

which is then passed into the PHP code using

data: "lastname=" + name,

and then retrieved in PHP using

$lastname = $_POST['lastname'];

So you can see the relevance of the id, through the JS variable name, the name (not the value) you assign to it when you call the PHP, and how you then retrieve that in PHP.

1 Like

I thought I really had messed up and had my variables misnamed, but those are all updated in the code when I switched to the new form. I will paste all of my active code below:

JS File

$("#contactForm").validator().on("submit", function (event) {
    if (event.isDefaultPrevented()) {
        // handle the invalid form...
        formError();
        submitMSG(false, "Please correct highlighted fields prior to submitting.");
    } else {
        // everything looks good!
        event.preventDefault();
        submitForm();
    }
});


function submitForm(){
    // Initiate Variables With Form Content
    var name = $("#name").val();
    var email = $("#email").val();
	var phone = $("#phone").val();
	var date = $("#date").val();
    var message = $("#message").val();

    $.ajax({
        type: "POST",
        url: "php/form-process.php",
        data: "name=" + name + "&email=" + email + "&phone=" + phone + "&date=" + date + "&message=" + message,
        success : function(text){
            if (text == "success"){
                formSuccess();
            } else {
                formError();
                submitMSG(false,text);
            }
        }
    });
}

function formSuccess(){
    $("#contactForm")[0].reset();
    submitMSG(true, "Message Submitted. We will be in touch with you shortly.")
}

function formError(){
    $("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
        $(this).removeClass();
    });
}

function submitMSG(valid, msg){
    if(valid){
        var msgClasses = "h5 text-center tada animated text-success";
    } else {
        var msgClasses = "h5 text-center text-danger";
    }
    $("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}

HTML File


                             <form role="form" id="contactForm" data-toggle="validator" class="shake">
        <div class="row">
            <div class="form-group col-sm-6">
                <label for="name" class="h4">Name</label>
                <input type="text" class="form-control" id="name" placeholder="Enter name" required data-error="Please enter a name.">
                <div class="help-block with-errors"></div>
            </div>
            <div class="form-group col-sm-6">
                <label for="email" class="h4">Email</label>
                <input type="email" class="form-control" id="email" placeholder="Enter email" required data-error="Please enter an email.">
                <div class="help-block with-errors"></div>
            </div>
        </div>
         <div class="row">
            <div class="form-group col-sm-6">
                <label for="phone" class="h4">Phone</label>
                <input type="text" class="form-control" id="phone" placeholder="Enter phone number" required data-error="Please enter a phone number.">
                <div class="help-block with-errors"></div>
            </div>
            <div class="form-group col-sm-6">
                <label for="date" class="h4">Date of Preferred Appointment</label>
                <input type="date" class="form-control" id="date" placeholder="Date" required data-error="Please enter a preferred date.">
                <div class="help-block with-errors"></div>
            </div>
        </div>
        <div class="form-group">
            <label for="message" class="h4 ">Message</label>
            <textarea id="message" class="form-control" rows="5" placeholder="Enter your message" required data-error="Please provide a message."></textarea>
            <div class="help-block with-errors"></div>
        </div>
        <button type="submit" id="form-submit" class="btn btn-success btn-lg pull-right ">Submit</button>
        <div id="msgSubmit" class="h3 text-center hidden"></div>
        <div class="clearfix"></div>
    </form>

PHP file


<?php

$errorMSG = "";

// NAME
if (empty($_POST["name"])) {
    $errorMSG = "Name is required ";
} else {
    $name = $_POST["name"];
}

// EMAIL
if (empty($_POST["email"])) {
    $errorMSG .= "Email is required ";
} else {
    $email = $_POST["email"];
}

// PHONE
if (empty($_POST["phone"])) {
    $errorMSG .= "Phone is required ";
} else {
    $email = $_POST["phone"];
}

// DATE
if (empty($_POST["date"])) {
    $errorMSG .= "Date is required ";
} else {
    $email = $_POST["date"];
}

// MESSAGE
if (empty($_POST["message"])) {
    $errorMSG .= "Message is required ";
} else {
    $message = $_POST["message"];
}


$EmailTo = "test@gmail.com";
$Subject = "New message received!";

// prepare email body text
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Phone: ";
$Body .= $phone;
$Body .= "\n";
$Body .= "Date Preferred for Appointment: ";
$Body .= $date;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";

// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);

// redirect to success page
if ($success && $errorMSG == ""){
   echo "success";
}else{
    if($errorMSG == ""){
        echo "Message was not sent.";
    } else {
        echo $errorMSG;
    }
}

?>

Is that really your actual live code now? You’ve run into the problem with copy and paste when adding fields…

// EMAIL
...
    $email = $_POST["email"];

// PHONE
...
    $email = $_POST["phone"];

// DATE
...
    $email = $_POST["date"];

At least that clears up why the date appears in the email address.

You also might have trouble trying to send the email using the form-fillers email address as the “From” address. Your mail server might prevent it, unless it’s on a domain that mail server is configured to send mail for.

Also, I’m not sure whether you need to handle stuff like spaces inside the message when you pass it using Ajax. The Ajax routine might already encode it, but it’s worth checking.

1 Like

Sloppy cut and paste on my behalf! Good catch! It’s good to go now!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.