JS, PHP and HTML form

jquery
php
#1

I have a form which i have create in HTML, but works with PHP and AJAX/Javascript. The form submits and works as it should, I receive an email, but it is blank. I am not sure why it isn’t working properly. If anyone could assit I would be greatful. I would also like to fit in a failer clause and perhaps some sort of Captcha, if I could guidence on that too please.

PHP;

```
<?php
	
	
	$status = array(
		'message'=>'Email sent!'
	);
	
		
if($_SERVER["REQUEST_METHOD"] == "POST"){
	$email_to = 'My@website';
    $name = ($_POST['name']); 
    $email = ($_POST['email']); 
    $subject = ($_POST['subject']); 
    $message = ($_POST['message']); 
	$headers = 'From: My Website';
	
    $body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;

    if (mail($email_to, $subject, $body, $headers))
	{

    echo json_encode($status); 
	}
}
```

JS;

var form = $('.contact-form');
	form.submit(function () {
	this = $(this);
		$.post($(this).attr('action'), function(data) {
		$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
	},'json');
	return false;
	});
```

HTML

```
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="PHP/sendemail.php" role="form">
                            <div class="row">
                              <div class="col-sm-6">
                                    <div class="form-group">
                                        <input type="text" id="name" name="name" class="form-control" required="required" placeholder="Name">
								  </div>
								</div>
                                <div class="col-sm-6">
                                  <div class="form-group">
                                    <input type="text" name="email" id="email" class="form-control" required="required" placeholder="Email address">
                                  </div>
                                </div>
                                <div class="col-sm-6 col-lg-12 col-md-12">
                                    <div class="form-group">
                                        <input type="text" name="subject" id="subject" class="form-control" required="required" placeholder="Subject">
                                  </div>
									
                              </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-12">
                                    <div class="form-group">
                                        <textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Message"></textarea>
                                    </div>
                                    <div class="form-group">
                                        <button type="submit" class="btn btn-danger btn-lg">Send Message</button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div><!--/.col-sm-6-->
```
#2

Define ‘it is blank’. Is it empty? or do you receive Name: Email: Subject etc just with no values.

#3

Hi Sorry, good point.

I receive the email with the $body only, no population. Example:

Name:

Email:

Subject:

Message:

#4

If you disable the JS does it work then?

#5

Yes it does, But i then don’t get the nice message just above the form, it goes to a blank page which just echo’s the ‘Email sent!’

#6

Your post command isnt sending a payload. You’ve specified the first, third, and fourth parameters, but missed the second.

#7

Thank you for your response.
I am sorry, but I am not good with JS and I cannot see what the parameter is that i am missing and where it should go

#8

In the doc here https://api.jquery.com/jquery.post/ it describes the parameters required for the function as:

jQuery.post( url [, data ] [, success ] [, dataType ] )

and as you can see, in your line of code

$.post($(this).attr('action'), function(data) {
		$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
	},'json');

You have the first parameter $(this).attr('action') - which is the destination specified in your form definition “action” tag. This is the ‘url’ parameter.

Your next parameter is function(data) { $this.prev().text(data.message).fadeIn().delay(3000).fadeOut();}, which is an in-line function definition specifying what to do with the returned data. This is your ‘success’ parameter.

Your final parameter is “Json”, which is the ‘dataType’ parameter - the format that you want the data returned in.

As you can see, you are missing the second parameter, called ‘data’ in the function definition I linked to. This is the data that you are passing into your PHP code, and as you don’t specify it, that’s why your email is blank.

So, the thing to do now is have a look around at ways you can gather form data in order to post it with Ajax. There seem to be several methods, and I’m not up to date in this stuff so I hesitate to suggest a specific one.

Once you’ve gathered the data from the form into a suitable JS variable, probably in JSON format, you need to stick it in the second position in your .post() call.

If you have a read through that link, there’s an example of how to gather data from a form and do something with it.

1 Like
#9

(Hint: Go back to that same doc reference…)

Send form data using Ajax requests

$.post( "test.php", $( "#testform" ).serialize() );
2 Likes
#10

Thank you, I will have a look at this later this evening. It all looks overwhelming, but with your hints and explanation, I will hopefully makes sense of it and get it working. Thank you again. I will let you know how I get on.

#11

Hi guys,

This is what I added below following your advice and it now works…so thank you.


$.post($(this).attr('action'),      $(this).serialize(),         function(data) {

I now need to work out adding error issues and a Captcha. If any ideas, please feel free to comment. thank you

1 Like
#12

Well as far as error issues go, first you have to identify all the possible errors that could occur. (even if one of the buckets is labelled ‘unspecified’)
Once you’ve come up with your desired error cases, you can put code in to handle them.

As far as a Captcha, i recommend following the instructions.

#13

ok thank you, i will research the error side more and let you know lol

#14

Hi,

I have added the below reCaptcha to my form and althought it all works, the form still sends without using th captcha. I have added the below code into my php ffile. Do I need to add anything else to get it to work?

        <form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="PHP/sendemail.php" role="form">
                            <div class="row">
                              <div class="col-sm-6">
                                    <div class="form-group">
                                        <input type="text" id="name" name="name" class="form-control" required="required" placeholder="Name">
								  </div>
								</div>
                                <div class="col-sm-6">
                                  <div class="form-group">
                                    <input type="text" name="email" id="email" class="form-control" required="required" placeholder="Email address">
                                  </div>
                                </div>
                                <div class="col-sm-6 col-lg-12 col-md-12">
                                    <div class="form-group">
                                        <input type="text" name="subject" id="subject" class="form-control" required="required" placeholder="Subject"> 
                                  </div>
									
                              </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-12">
                                    <div class="form-group">
                                        <textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Message"></textarea>
                                    </div>
									
								  <div class="g-recaptcha" data-sitekey="369852"></div>
   								
									<br>
                                    <div class="form-group">
                                        <button type="submit" class="btn btn-danger btn-lg">Send Message</button>
                                    </div>
                                </div>
                            </div>
                        </form>
<?php
	
	
	$status = array(
		'message'=>'Email sent!'
	);
	 

if($_SERVER["REQUEST_METHOD"] == "POST"){
	
    $secretKey = '78912';
    $captcha = $_POST['g-recaptcha-response'];
	
    $email_to = 'website.co.uk';
    $name = ($_POST['name']); 
    $email = ($_POST['email']); 
    $subject = ($_POST['subject']); 
    $message = ($_POST['message']); 
	$headers = 'From: KJW Technical Solutions Website';
	
    $body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;

    if (mail($email_to, $subject, $body, $headers))
	{

    echo json_encode($status); 
	}
}
#16

What version of recaptcha are you using here?

As I understand it, once you’ve submitted the form you then need to very the captcha response using CURL or something like it. So your PHP code is sending the email because all you do is get the response but don’t check whether it’s valid or not.

Maybe you’re using a later version that works differently. In mine I have to grab the response, post it to the ‘verify’ site, and get the confirmation from there.

#17

It is reCaptcha V2

I have seen some different example code, but because i’m not confident and also, I finally got the form working properly, I don’t want to go an mess it up.

#18

Oh, that’s the version I used. I wanted a page that would show email addresses but only if the recaptcha was verified.

I added the re-captcha thing to a page:

      <div class="g-recaptcha" data-sitekey="my-site-key" data-callback="cbtest"></div>

and a callback function

	function cbtest(response) {
	// now, send the response to be verified
	var dispdiv = document.getElementById("result");
	$.ajax({
	url: "http://www.mysite/recaptcha_verify.php",
	type: "POST",
	data: {response: response},
	  }).done(function(data, status, xhr) {
	  var ver = data.substring(0,2);
	  if (ver == "no") {
	  dispdiv.innerHTML = "<p>Sorry, there was a verification problem.</p>";
	  } else if (ver == "OK") { 
	  var out = data.substring(3);
	  dispdiv.innerHTML = "<p>The contact details you requested are:<br />" + out + "</p>";
	  } // end of verification response check
	  })
	  };

and my PHP code goes off to do the verification, called by the above function:

<?php
if (isset($_POST['response'])) { 
$response = $_POST['response']; }
else {
	echo "no1";
	exit;
}

$url = "https://www.google.com/recaptcha/api/siteverify";
$secret = "my-secret";

// create the output
 $url = $url."?secret=".$secret. "&response=".$response;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 15);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, TRUE); 
        $curlData = curl_exec($curl);
        curl_close($curl);
	
   $captcha_success = json_decode($curlData, TRUE);
   
   if ($captcha_success['success'] == false) {
       echo "noF";
   }
   else if ($captcha_success['success'] == true) {
       $out = // whatever email address I need to display
       echo "OK|" . $out;
   }
?>

I think the above should work - I’ve removed some bits of code that actually pick the email address to show - I pass in a selection number and grab that out of an array. But it shows the next stage of the recaptcha verification. I basically found the code on the web, and I found at the time there were a lot that only looked at the first response, but didn’t actually check using site-verify that it was valid.

1 Like
#19

Thank you,

When I get some time, I will look at my code and try and implement what you have advised and given within it.

I will then let you know how I get on.