簡體   English   中英

提交表單后,為什么我的頁面會刷新?

[英]Why is my page refreshing after submitting a form?

問題

我將嘗試在不使事情復雜化的情況下包含盡可能多的信息,但是當我提交表單時,頁面會刷新,從而關閉帶有表單的選項卡,這是我的問題。 然后,用戶需要再次單擊選項卡以查看反饋。

背景信息。

我有一個使用JavaScript打開和關閉“標簽”(divs)的網頁,在這些標簽中的一個上,我有一個表單,其中POST是用戶輸入數據到php腳本的,然后將數據發送到電子郵件地址,然后重定向回原始頁面。 但是,當腳本重定向回頁面時,該選項卡關閉,從而使用戶重新單擊該選項卡以再次打開它,以查看來自腳本的自動反饋。

我檢查了什么

我已經檢查過了,它不是導致刷新的重定向,因為在將POST形式傳遞給自身時仍然會發生刷新。

有問題的網站

有人有什么想法嗎?

這是表單的HTML,位於查詢“標簽”中。

           <div class='content one'>
      <div id="contact-form" class="clearfix">
        <P>Quick And Easy!</P>
        <br/>
        <P>Fill out our super swanky contact form below to get in touch with us! Please provide as much information as possible for us to help you with your enquiry.</P>
        <br/>
        <?php
            //init variables
            $cf = array();
            $sr = false;

            if(isset($_SESSION['cf_returndata'])){
                $cf = $_SESSION['cf_returndata'];
                $sr = true;
            }
            ?>
        <ul id="errors" class="<?php echo ($sr && !$cf['form_ok']) ? 'visible' : ''; ?>">
          <li id="info">There were some problems with your form submission:</li>
          <?php 
                if(isset($cf['errors']) && count($cf['errors']) > 0) :
                    foreach($cf['errors'] as $error) :
                ?>
          <li><?php echo $error ?></li>
          <?php
                    endforeach;
                endif;
                ?>
        </ul>
        <p id="success" class="<?php echo ($sr && $cf['form_ok']) ? 'invisible' : ''; ?>">Now sit back and relax while we go to work on your behalf, we'll keep you updated with information on our results and if you have any questions then we welcome your calls or emails on 078675675446 or isaaclayne@southwestcarfinder.co.uk</p>
         <form method="POST" action="process.php">
          <label for="enquiry">Make: </label>
           <select id="make" name="make">
             <option value="Ford" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['make'] == 'Ford') ? "selected='selected'" : '' ?>>Ford</option>
             <option value="BMW" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['make'] == 'BMW') ? "selected='selected'" : '' ?>>BMW</option>
             <option value="Vauxhall" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['make'] == 'Vauxhall') ? "selected='selected'" : '' ?>>Vauxhall</option>
           </select>
           <label for="Model">Model: <span class="required">*</span></label>
           <input type="text" id="model" name="model" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['model'] : '' ?>" placeholder="Model of Car" required autofocus />
           <label for="name">Name: <span class="required">*</span></label>
           <input type="text" id="name" name="name" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['name'] : '' ?>" placeholder="John Doe" required autofocus />
           <label for="email">Email Address: <span class="required">*</span></label>
           <input type="email" id="email" name="email" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['email'] : '' ?>" placeholder="johndoe@example.com" required />
           <label for="telephone">Telephone: </label>
           <input type="tel" id="telephone" name="telephone" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['telephone'] : '' ?>" />
           <label for="Budget">Your Budget: </label>
           <select id="enquiry" name="enquiry">
             <option value="300 or less" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'General') ? "selected='selected'" : '' ?>>£300 or less</option>
             <option value="400 or more" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Sales') ? "selected='selected'" : '' ?>>£400</option>
             <option value="500 or more" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['enquiry'] == 'Support') ? "selected='selected'" : '' ?>>£500 or more</option>
           </select>
           <label for="message">Additional Info: <span class="required">*</span></label>
           <textarea id="message" name="message" placeholder="Your message must be greater than 20 charcters" required data-minlength="20"><?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['message'] : '' ?></textarea>
           <span id="loading"></span>
           <input type="submit" value="Find My Car!" id="submit-button" />
           <p id="req-field-desc"><span class="required">*</span> indicates a required field</p>
         </form>
         <?php unset($_SESSION['cf_returndata']); ?>
       </div>
       <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> 
       <script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-    1.5.1.min.js"%3E%3C/script%3E'))</script> 
       <script src="js/plugins.js"></script> 
       <script src="js/script.js"></script> 
       <!--[if lt IE 7 ]>
     <script src="js/libs/dd_belatedpng.js"></script>
     <script> DD_belatedPNG.fix('img, .png_bg');</script>

     <![endif]--> 
     </div>

PHP腳本

<?php
if( isset($_POST) ){

    //form validation vars
    $formok = true;
    $errors = array();

    //sumbission data
    $ipaddress = $_SERVER['REMOTE_ADDR'];
    $date = date('d/m/Y');
    $time = date('H:i:s');

    //form data
    $make = $_POST['make'];
    $model = $_POST['model'];
    $name = $_POST['name']; 
    $email = $_POST['email'];
    $telephone = $_POST['telephone'];
    $enquiry = $_POST['enquiry'];
    $message = $_POST['message'];

    //validate form data

    //validate name is not empty
    if(empty($name)){
        $formok = false;
        $errors[] = "You have not entered a name";
    }

    //validate email address is not empty
    if(empty($email)){
        $formok = false;
        $errors[] = "You have not entered an email address";
    //validate email address is valid
    }elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        $formok = false;
        $errors[] = "You have not entered a valid email address";
    }

    //validate message is not empty
    if(empty($message)){
        $formok = false;
        $errors[] = "You have not entered a message";
    }
    //validate message is greater than 20 charcters
    elseif(strlen($message) < 20){
        $formok = false;
        $errors[] = "Your message must be greater than 20 characters";
    }

    //send email if all is ok
    if($formok){
        $headers = "From: Info@Columbus.com" . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

        $emailbody = "<p>You have recieved a new message from the enquiries form on your website.</p>
                      <p><strong>Name: </strong> {$name} </p>
                        <p><strong>Telephone: </strong> {$telephone} </p>
                        <p><strong>Email Address: </strong> {$email} </p>
                        <br/>
                       <p><strong>Make: </strong> {$make} </p>
                       <p><strong>Model: </strong> {$model} </p>
                      <p><strong>Budget: </strong> {$enquiry} </p>
                      <br/>
                      <p><strong>Message: </strong> {$message} </p>
                      <p>This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}</p>";



        mail("dancundy@hotmail.com","New Enquiry",$emailbody,$headers);

    }

    //what we need to return back to our form
    $returndata = array(
        'posted_form_data' => array(
            'name' => $name,
            'email' => $email,
            'telephone' => $telephone,
            'enquiry' => $enquiry,
            'message' => $message
        ),
        'form_ok' => $formok,
        'errors' => $errors
    );


    //if this is not an ajax request
    if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'){
        //set session variables
        session_start();
        $_SESSION['cf_returndata'] = $returndata;

        //redirect back to form
        //header('location:' . $_SERVER['HTTP_REFERER']);
        header('Location: index.php#contact-form'  );
    }
}

?>

您提交表單時正在發出POST請求。 默認情況下,POST請求通過瀏覽器發送到服務器的HTTP請求進行傳輸,因此瀏覽器需要加載導致站點刷新的新數據。

如果您希望瀏覽器不刷新,則需要在客戶端使用Javascript進行AJAX請求。 您可以使用jQuery完成此操作。

嘗試這個

$('form').submit(function(e)
{
e.preventDefault();
})

謝謝@saman和@gpopoteur,

您的答案很好並且可以正常工作,而在我的測試服務器上卻沒有。

這是最終要工作的。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"    type="text/javascript"></script><script>

$('#form1').submit(function(e)
{
event.preventDefault();
 $.ajax({
     type : 'POST',
     url : 'process.php',
     data : $(this).serialize(),
     success : function(response) {

     }
   });
});

我確實發現的是盡管腳本沒有返回任何內容。 EI是否提供任何驗證信息或返回的數據? 沒有太大的問題,我將解決。 再次感謝

暫無
暫無

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

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