При нажатии на кнопку контактной формы сайт перенаправляется на пользовательскую запись. - PullRequest
1 голос
/ 20 сентября 2019

У меня есть этот WordPress сайт с пользовательским типом поста, называемым обзорами, циклом и контактной формой на странице.Когда я нажимаю кнопку «Отправить» на странице контактов, независимо от того, соответствует ли содержимое формы регулярному выражению, она перенаправляет страницу на / reviewa / random name

Я удалил часть «обзоров» сайта иформа работает.

Я хотел бы, чтобы форма отправляла электронное письмо без перенаправления сайта на / reviews / randomName

$(function() {
  var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

  $('#contact-form').submit(function(e) {

    $clientName = $("#contactName").val();

    var valid = true;

    // Remove any confirmation messages
    $('p.confirmation').remove();

    // Validate all fields that have a class of .required-field
    $('.required-field').each(function() {

      // Remove error class from all inputs and textareas and delete error messages before checking form again
      $(this).removeClass('error').next('p').remove();

      if ($(this).val().trim() === '' && $(this).attr('id') != 'email') {
        $(this).addClass('error').parent().append('<p class="error">Please enter a ' + $(this).prev().html().toLowerCase() + '</p>');
        valid = valid && false;
      } else if ($(this).attr('id') === 'email') {

        if (!$(this).val().trim().match(re)) {
          $(this).addClass('error').parent().append('<p class="error">Please enter a valid email address</p>');
          valid = valid && false;
        }
      }
    });

    if (valid) {

      var formInput = $(this).serialize();

      $.post($(this).attr('action'), formInput, function(data) {
        $('#contact-form').before('<p class="confirmation">Thanks ' + $clientName + ', your email was successfully sent. We will be in touch soon.</p>');
        _gaq.push(['_trackEvent', 'Contact form', 'Contact form submitted']);
      });
    }

    e.preventDefault();
  });
});
<div id="reviews">
  <h2>Our reviews</h2>
  <div id="slider" class="flex-container">
    <div class="flexslider">
      <ul class="slides">
        <?php $new = new WP_Query('post_type=reviews&    posts_per_page=-1');
        while ($new->have_posts()) : $new->the_post(); ?>
        <li>
          <?php echo the_post_thumbnail('portfolio-thumb');?>

          <span class="review"> <?php the_content(); ?></span>
          <span class="name"> <?php the_title(); ?></span>

        </li>
        <?php endwhile;?>
      </ul>
    </div>
  </div>
</div>
<div id="contact">
  <h2>To contact the instructor, plese enter your details below</h2>
  <?php
    if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['submitted'])){

        //Check name
        if(trim($_POST['contactName']) === '') {
            $nameError = true;
            $hasError = true;
        }else{
            $name = trim($_POST['contactName']);
        }

        //Check company name
        if(trim($_POST['companyName']) === '') {
            $companyNameError = true;
            $companyNameError = true;
        }else{
            $companyName = trim($_POST['companyName']);
        }

        //Check address
        if(trim($_POST['address']) === '') {
            $addressError = true;
            $addressError = true;
        }else{
            $address = trim($_POST['address']);
        }

        // Check email address exists and is valid
        if(trim($_POST['email']) === '')  {
            $emailError = 'Please enter your email address.';
            $hasError = true;
        }else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+.[A-Z]{2,4}$",trim($_POST['email']))){
            $emailError = 'You entered an invalid email address.';
            $hasError = true;
        }else{
            $email = trim($_POST['email']);
        }

        if(trim($_POST['telNumber']) === '') {
            $telError = true;
            $hasError = true;
        }else{
            $telephone = trim($_POST['telNumber']);
        }



        //Check message
        if(trim($_POST['message']) === ''){
            $messageError = true;
            $hasError = true;
        }else{
            $message = stripslashes(trim($_POST['message']));
        }

        //If there is no error, send the email
        if(!isset($hasError)){

            $emailTo = 'randomEmail@mail.com';
            $subject = 'Contact from the Contact Us page';
            $body = "Name: $name \n Email: $email \n Telephone:     $telephone \n  Poxtcode: $address . \n Message:\n$message";
            $headers = 'From: randomWebsite.com, <'.$emailTo.'>' . "\n" . "\n" .'Reply-To: ' . $email;

            ssmtp($emailTo, $subject, $body, $headers);

            $emailSent = true;

        }
    }
    ?>



    <?php if($emailSent == true) { ?>
    <p class="confirmation">Thanks,
      <?php echo $name;?>, your email was successfully sent. We will be in touch soon.</p>
    <?php } ?>



    <form action="<?php the_permalink(); ?>" id="contact-form" method="post" novalidate>
      <ul>
        <li>
          <input type="text" placeholder="Name (required)" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])){echo $_POST['contactName'];} ?>" class="required-field" />
          <?php if($nameError) { ?>
          <p class="error">Please enter your name.</p>
          <?php } ?>
        </li>


        <li>
          <input type="text" placeholder="Postcode (required)" name="address" id="address" value="<?php if(isset($_POST['address'])){echo $_POST['address'];} ?>" class="required-field" />
          <?php if($addressError) { ?>
          <p class="error">Please enter your postcode.</p>
          <?php } ?>
        </li>

        <li>
          <input type="tel" placeholder="Mobile number (required)" name="telNumber" id="telNumber" value="<?php if(isset($_POST['telNumber'])){echo $_POST['telNumber'];} ?>" />
          <?php if($telError) { ?>
          <p class="error">Please enter your mobile number.</p>
          <?php } ?>
        </li>

        <li>
          <input type="email" placeholder="Email (required)" name="email" id="email" value="<?php if(isset($_POST['email'])){echo $_POST['email'];} ?>" class="required-field" />
          <?php if($emailError) { ?>
          <p class="error">
            <?php echo $emailError;?>
          </p>
          <?php } ?>
        </li>

        <li class="textarea">
          <textarea name="message" placeholder="Message (required)" id="message" rows="20" cols="30" class="required-field"><?php if(isset($_POST['message'])){echo stripslashes($_POST['message']);} ?></textarea>
          <?php if($messageError) { ?>
          <p class="error">Please enter a message.</p>
          <?php } ?>
        </li>
        <li>
          <input type="hidden" id="submitted" name="submitted" />
          <button class="button" ">Send</button>
            </li>
        </ul>
    </form>



</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...