Skip to content
Advertisement

run PHP script in JS file

I have minimal knowledge in php and js. Im trying to get value from my form once submit button has been click then trigger my php script.

Js file:

document.getElementById('form')
    .addEventListener('submit', function (event) {
        event.preventDefault();

        let response = grecaptcha.getResponse();
        if (validateFields() && !response.length == 0) {
            console.log('got here');
            var data = new FormData(document.getElementById('form'));
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'form-to-email.php');
            xhr.onload = function () {
                console.log(this.response);
            };
            xhr.send(data);
            return false;
        }
        document.getElementById('button').style.cursor = 'not-allowed';
});

Here’s my php script:

<?php
// Google reCAPTCHA API key configuration 
$siteKey     = 'siteKey';
$secretKey     = 'secretKey';

if (isset($_REQUEST['submit'])) {
  $to = "example@mail.com"; // this is your Email address
  $from = $_POST['email']; // this is the sender's Email address
  $name = $_POST['name'];
  $subject = "Form submission";
  $message = $name . " wrote the following:" . "nn" . $_POST['message'];

  if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
    // Verify the reCAPTCHA response 
    $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secretKey . '&response=' . $_POST['g-recaptcha-response']);

    // Decode json data 
    $responseData = json_decode($verifyResponse);

    // If reCAPTCHA response is valid 
    if ($responseData->success) {
      $headers = "From:" . $name . '<' . $from . '>' . PHP_EOL;
      $headers .= "Reply-To:" . $to . PHP_EOL;
      $headers .= "MIME-Version 1.0" . PHP_EOL;
      $headers .= "Content-Type: text/html; charset=UTF-8" . PHP_EOL;
      $headers .= "X-Mailer: PHP/" . phpversion();
      $status = mail($to, $subject, $message, $headers);

      echo "<pre>";
      var_dump($status);
      if ($status) {
        echo '<p>Your message has been sent. We will get in touch with you soon. Thank you!</p>';
      } else {
        echo '<p>Something went wrong. Please try again!</p>';
      }
    } else {
      echo 'error';
    }
  } else {
    echo 'Please check on the reCAPTCHA box.';
  }
}
?>

Here’s my form code in index.php. I have 3 fields name, email and message:

<?php include_once 'form-to-email.php';?>
    <form id="form" method="post" action="">
        <div class="input-group">
            <input type="text" id="name" name="name" class="input-demo" placeholder="Your Name">
            <span id="invalid-name">
                Please enter at least 2 chars
            </span>
        </div>
        <div class="input-group">
            <input id="email" type="email" name="email" class="input-demo" placeholder="Email Address">
            <span id="invalid-email">
                Please enter valid email
            </span>
        </div>
        <div class="input-group">
            <textarea id="message" name="message" placeholder="Message">
            </textarea>
            <span id="invalid-message">
                Please write something for us
            </span>
        </div>
        <div class="g-recaptcha" data-sitekey="<?php echo $siteKey; ?>">
        </div>
        <input type="submit" name="submit" id="button" class="demo" value="Book a Demo">
    </form>

I get console.log empty values. Is this the right path or calling php is simply not doable?

Update
It now echos true and message sent.

enter image description here

Advertisement

Answer

Based on this answer, change the way you’re calling the php function.

document.getElementById('form')
    .addEventListener('submit', function (event) {
        event.preventDefault();

        let response = grecaptcha.getResponse();
        if (validateFields() && !response.length == 0) {
            var data = new FormData(document.getElementById('form'));
            
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if(xhr.readyState == 4 && xhr.status == 200) {
                    console.log(xhr.responseText);
                }
            }

            xhr.open('POST', 'form-to-email.php?submit'); //don't forget submit here
            xhr.send(data);
        }
        document.getElementById('button').style.cursor = 'not-allowed';
});

Also, try using $_REQUEST instead of $_POST in PHP file, as in:

if (isset($_REQUEST['submit'])) {
    echo 'HERE IN PHP';
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement