Задать вопрос
@Kryptonit

Как вставить php в js?

у меня есть файл index.php, в нём тело сайта с формой
<form action="#" method="POST">
                    <div class="dannue">
                        <input type="text" name="fio" placeholder="Имя" required="">
                        <input type="text" name="email" placeholder="Почта" required="">
                        <input type="hidden" name="token" id="token" value="03AGdBq26YYdWHX94usO0FU6">
                    </div>
                    <input type="text" name="thema" id="inp" placeholder="Тема" required="">
                    <textarea name="mess" cols="30" rows="10" placeholder="Сообщение" required=""></textarea>
                    <button id="send" type="submit">Отправить</button>       
                </form>


форму обрабатывает google captcha, всё работает корректно, определяет бот или человек.
Код снизу обрабатывает форму(нижняя часть файла index.php) и связывается с google api:

<script>
    document.querySelector('form').addEventListener('submit', (e) =>{

    e.preventDefault();

    let tk = '';

        grecaptcha.ready(function() {
          grecaptcha.execute('6LfjGsMZAAAAAPxwEON9oAMztQGcRx', {action: 'homepage'}).then(function(token) {
              tk = token;
              document.getElementById('token').value = token;
              

              const data = new URLSearchParams();
              for(const pair of new FormData(document.querySelector('form'))){
                data.append(pair[0], pair[1]);
              }

              fetch('send.php',{
                method: 'post',
                body: data,
              })
              .then(response => response.json())
              .then(result => {
                if(result['om_score'] >= 0.5){
                  console.log('человек');
                  
                  <?php
                    $fio = $_POST['fio'];
                    $email = $_POST['email'];
                    $mess = $_POST['mess'];
                    $thema = $_POST['thema'];
                    $fio = htmlspecialchars($fio);
                    $email = htmlspecialchars($email);
                    $mess = htmlspecialchars($mess);
                    $thema = htmlspecialchars($thema);
                    $fio = urldecode($fio);
                    $thema = urldecode($thema);
                    $mess = urldecode($mess);
                    $email = urldecode($email);
                    $fio = trim($fio);
                    $email = trim($email);

                    if (mail("eor01000@gmail.com", "Тема".$thema, "".$fio.". E-mail: ".$email. "сообщение:".$mess ,"eor01000@gmail.com \r\n"))
                     {     header('Location: success-page.html'); 
                    } else { 
                        header('Location: fail-page.html');
                   }
                    ?>
                }else{
                  console.log('бот');
            }
          });
        });
      });
  });
</script>


так же есть файл send.php(если нужен)

<?php

$captcha;

if(isset($_POST['token'])){
  $captcha = $_POST['token'];
}

$secretkey = '6LfjGsMZAAAAAAt9_XdcVXP-sfL8y1';

$url = 'https://www.google.com/recaptcha/api/siteverify?secret='.$secretkey.'&response='.$_POST['token'];

$response = file_get_contents($url);
$responsekeys = json_decode($response, true);
header('Content-type: application/json');
if($responsekeys["success"] && $responsekeys["score"] >= 0.5){
  echo json_encode(array('success' => 'true', 'om_score' => $responsekeys["score"], 'token' => $_POST['token']));
}else {
  echo json_encode(array('success' => 'false', 'om_score' => $responsekeys["score"], 'token' => $_POST['token']));
}

?>


в index.php, если внимательно посмотрите, есть строки:

<?php
                    $fio = $_POST['fio'];
                    $email = $_POST['email'];
                    $mess = $_POST['mess'];
                    $thema = $_POST['thema'];
                    $fio = htmlspecialchars($fio);
                    $email = htmlspecialchars($email);
                    $mess = htmlspecialchars($mess);
                    $thema = htmlspecialchars($thema);
                    $fio = urldecode($fio);
                    $thema = urldecode($thema);
                    $mess = urldecode($mess);
                    $email = urldecode($email);
                    $fio = trim($fio);
                    $email = trim($email);

                    if (mail("eor01000@gmail.com", "Тема".$thema, "".$fio.". E-mail: ".$email. "сообщение:".$mess ,"eor01000@gmail.com \r\n"))
                     {     header('Location: success-page.html'); 
                    } else { 
                        header('Location: fail-page.html');
                   }
                    ?>


после того, как скрипт определяет, что пишет человек, он должен выполнить эти строки на php, однако страничку с успехом или фейлом он не выводит, в браузере никаких ошибок абсолютно нет, я так думаю, что код не видится браузером, как это исправить?
  • Вопрос задан
  • 1350 просмотров
Подписаться 1 Простой 1 комментарий
Решения вопроса 1
Stalker_RED
@Stalker_RED
Никак не вставить, это совсем по другому работает.
Ваш js выполняется в браузере у пользователя, когда он заходит на страницу. А php код выполняется у вас на сервере, еще ДО отправки страницы.
Если вы хотите чтобы действия пользователя как-то повлияли на сервер, то нужно отправить запрос на сервер, при помощи xhr или fectch, например.
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы