簡體   English   中英

在 JS 文件中運行 PHP 腳本

[英]run PHP script in JS file

我對 php 和 js 知之甚少。 一旦單擊提交按鈕,我試圖從我的表單中獲取價值,然后觸發我的 php 腳本。

.js 文件:

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';
});

這是我的 php 腳本:


<?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:" . "\n\n" . $_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.';
  }
}
?>

這是我在 index.php 中的表單代碼。 我有 3 個字段名稱,email 和消息:

<?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>

我得到 console.log 空值。 這是正確的路徑還是調用 php 根本不可行?

更新
它現在回顯 true 並發送消息。

在此處輸入圖像描述

根據您的問題,您只是希望提交表單並訪問 php 腳本中的值。 但您似乎正在嘗試通過 ajax 請求提交表單。 第一個開始的地方是您的 javascript 代碼。 我看到的第一件事是您正在調用幾個未定義的函數,因此您永遠不會通過 if 檢查並到達應該說“到這里”的地方:

        let response = grecaptcha.getResponse();
        if (validateFields() && !response.length == 0) {
            console.log('got here'); // you never get to this point

grecaptcha尚未定義,我沒有看到validateFields()的任何 function 定義,因此也失敗了。 作為調試時的臨時修復,請像這樣注釋掉if檢查,以便您可以專注於xhr請求:

document.getElementById('form')
    .addEventListener('submit', function (event) {
        event.preventDefault();
   // Comment out the following two lines
   // so you can focus on getting the XHR request to work
   //     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;
     //   } Comment out the closing bracket to match the comments from above
        document.getElementById('button').style.cursor = 'not-allowed';
});

好的,現在當您點擊提交時,您應該將表單數據發送到您的 php 腳本。 要測試 php 腳本中顯示的內容,您可以提前退出以查看 $_POST 變量的內容。

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

// Echo out the word success to make sure you got to this point.
// Then echo out the contents of your $_POST variable to see what is in it.
echo "Success";
var_dump($_POST);
exit; // exiting here bails out early.

// When you var_dump out your $_POST variable you will notice that
// $_POST['submit'] is not set since you don't have an input field
// for that value.

if (isset($_POST['submit'])) {
  $to = "example@email.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:" . "\n\n" . $_POST['message'];

. . . 

現在,由於您決定通過 ajax 執行此操作,因此查看 echo 語句和 var_dump 會有點棘手。 要確定它是否正常工作,您需要使用您的開發工具網絡選項卡(F12 -> 網絡)。 在網絡選項卡下,您將看到如下內容: 開發工具網絡選項卡 每次點擊提交時,它都應該顯示一個新行,表示對該服務器的請求。 您可以 select 一行並檢查有效負載、預覽、響應選項卡以查看發送的內容和接收的內容。

我希望這有助於為您指明正確的方向。 我不打算討論驗證重新驗證碼和表單驗證的問題。 一旦您使基本表格起作用,這些就是另一個問題的主題。

干杯!

根據這個答案,改變你調用 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';
});

另外,嘗試在 PHP 文件中使用$_REQUEST而不是$_POST ,如下所示:

if (isset($_REQUEST['submit'])) {
    echo 'HERE IN PHP';
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM