Link to home
Start Free TrialLog in
Avatar of David Schure
David Schure

asked on

Contact Form Stopped Working

Contact form was working fine then it stopped,  Any help is appreciated. Thank you.

https://www.alessandrocoli.com/#contactcontact.php
Avatar of Kimputer
Kimputer

change your if statement:


if($_SERVER['REQUEST_METHOD'] == "POST")

Open in new window

Avatar of David Schure

ASKER

Thank you.  I have several "If Statements"  exactly which one? Thank you.

The one that looks like it most:


if(isset($_POST)) {

Open in new window


Hey David,

First off, what do you mean by 'stopped'. The page you've linked to doesn't have a contact form on it. It does have a Mailing List form on it, so maybe you're referring to that.

If so, you have a few problems with it. Firstly, you're submitting the page via AJAX, but you haven't set the method, so by default, it's making a GET request, not a POST request . Add the method to your AJAX call:

$.ajax({
    url: 'contact.php',
    dataType: 'json',
    data: $("#myform").serialize(),
    method : 'post'
}).done(function(response) {

Open in new window

Secondly, in your contact.php script, you're trying to read 3 keys from the POST array - name, email and message. The input fields in your contact form are called name, postal_code and email_address, so you'll need to read those:

$name = $_POST['name'];
$postalCode = $_POST['postal_code'];
$emailAddress = $_POST['email_address'];

Open in new window

You'll obviously need to edit your script to deal with these fields correctly.

When a request to a page is made, there is always a POST array (empty if nothing been submitted, so using if (isset($_POST) will always return true. Either use the method that Kimputer mentioned, or check whether it's empty:  if (!empty($_POST)

Sort those few problems out and see how you get on
Thank you.  You are correct.It is the Mailing List.  I changed the field names, but I am not sure where to place the Ajax part.

<?php
$error		= '';
$name		= '';
$emailAddress	= '';
$postalCode	= '';
		
if(isset($_POST)) {	
	$name = $_POST['name'];
	$postalCode = $_POST['postal_code'];
	$emailAddress = $_POST['email_address'];
	
	if(trim($name) == '') {
		$error = 'Attention! You must enter your name.';
	} else if(trim($emailAddress) == '') {
		$error = 'Attention! Please enter a valid email address.';
	} else if(!isEmail($emailAddress)) {
		$error = 'Attention! You have entered an invalid e-mail address, try again.';
	}

	if(trim($name) == '') {
		$error = 'Attention! Please enter a name.';
	} else if(trim($postalCode) == '') {
		$error = 'Attention! Please enter your postal code.';
	}

	if($error == '') {

		if(get_magic_quotes_gpc()) {
			$message = stripslashes($message);
		}
		$address = "smg@schuremediagroup.com";
		$e_subject = 'SMG You\'ve been contacted by ' . $name . '.';

		$e_body = "Alessandro You have been contacted by $name. Message is.\r\n\n";
		$e_content = "\"$message\"\r\n\n";

		$e_reply = "You can contact $name via email, $email";
		$headers = "From: smg@schuremediagroup.com";

		$msg = $e_body . $e_content . $e_reply;
		
		mail($address,$e_subject,$msg,$headers);
		
		echo json_encode(array('result' => 'success'));
	} else {
		echo json_encode(array('result' => 'error', 'errors' => array($error)));
	}
}


function isEmail($email) { // Email address verification, do not edit.
	return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}

Open in new window

Hi David,

The AJAX call is done in Javascript, so the code for that part is in your js/main.js file, towards the bottom
Thank you.  Did this
$(function() {
  $("#myform").on('submit', function(e) {
    e.preventDefault();
    $.ajax({
      url: 'contact.php',
      dataType: 'json',
      data: $("#myform").serialize(),
	  method : 'post'
    }).done(function(response) {
      if (response == true) {
        $("#myform").hide();
        $("#results").text("Thanks!").show();
      }
    });
  });
});

Open in new window


Along with the changes in the PHP file.  Still not functioning.
Right,

Well your Mailing List form is now submitting correctly and generating the success message from your PHP script, so you know it's getting that far.

Unfortunately, in debugging terms, pretty much the worse thing a developer has to deal with is an error report along the lines of "It doesn't work". That could literally be a hundred different things, so you're gonna have to give us a little more info. What exactly is it that's not working? Are you getting any errors? How do expect it to function? What is it not doing?

As it stands, we've fixed the Javascript issues and your PHP issues are resolved.

The only other I can see that's a problem, is the response from your PHP script is this:

echo json_encode(array('result' => 'success'));

But in your JQuery code, you're checking for this:

if (response == true) {

It may be that you need to be checking for this:

if (response.result == 'success') {
Have you got a copy of the code from when it was working? The problems you're fixing make very little sense for a form that was previously working; the code you're providing looks unfinished.
Sorry no copy of previous code.  I haven't touched this in a few months.  What should be happening is, If yyou leave a field blank it would say whatever field is incorrect when you hit the Submit button.  If all fields are correct then when you hit submit it would say "Thanks".
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you Chris!  That last bit did it!   I still don't understand why it stopped working.  But it is now.  Thank you so very much!
No worries David
Make sure you make a backup of your code, and keep it somewhere safe. That will prevent similar problems happening again in future ie where your code stops working for an unexplained reason, and you have no backup.