提交表单后,为什么我的页面会刷新?

时间:2014-01-27 14:14:52

标签: javascript php html5 forms

问题

我会尝试尽可能多地包含尽可能多的信息而不会使事情变得复杂,但我有一个问题,即当我提交表单时,页面会刷新,从而关闭带有表单的选项卡。然后,用户需要再次单击选项卡以查看反馈。

背景信息。

我有一个使用JavaScript打开和关闭“标签”(div)的网页,在其中一个标签上我有一个表格,用户将数据输入到php脚本,然后将数据发送到电子邮件地址然后重定向回原始页面。但是,当脚本重定向回页面时,选项卡将关闭,从而使用户重新单击选项卡以再次打开它以查看脚本的自动反馈。

我检查了什么

我已经检查过,并不是导致刷新的重定向,因为当表单POST自身时它仍然会发生。

The website in question

有没有人有任何想法?

以下是表单的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'  );
    }
}

?>

3 个答案:

答案 0 :(得分:5)

提交表单时,您正在发出POST请求。默认情况下,POST请求通过浏览器发送到服务器的HTTP请求,因此浏览器需要加载导致站点刷新的新数据。

如果您希望浏览器不刷新,那么您需要在客户端使用Javascript执行AJAX请求。您可以使用jQuery来完成此任务。

答案 1 :(得分:1)

试试这个

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

答案 2 :(得分:1)

谢谢@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) {

     }
   });
});

我找到的是虽然脚本没有返回任何内容。 E.我是否有任何验证信息或返回的数据?没有太大的问题,我会创造一个解决方案。再次感谢

相关问题