简体   繁体   中英

Why is my page refreshing after submitting a form?

Problem

I will try to include as much information as possible without complicating things, but i have a problem where when i submit a form the page refreshes thus closing the tab with the form on. The user then needs to click on the tab again to view the feedback.

Background info.

I have one webpage using JavaScript to open and close "tabs" (divs), on one of these tabs i have a form which POST's the user inputted data to a php script which then sends the data to an email address and then redirects back the the original page. However when the script redirects back to the page the tab is closed thus making the user re-click on the tab to open it again to see the automated feedback from the script.

What i have checked

I have checked and it is not the redirect causing the refreshing as it still happens when the form POST's to itself.

The website in question

Does anyone have any ideas?

Here is the HTML for the form, which is in the enquiry 'tab'.

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

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

?>

You are making a POST request when you submit the form. POST request by default travel through an HTTP request that the browser sends to the server, and therefore the browser needs to load the new data that causes the site to refresh.

If you want the browser to not refresh then you need to do an AJAX request using Javascript on the client side. You can use jQuery to accomplish this.

try this

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

Thank you @saman and @gpopoteur,

Your answers are great and do work, just wasn't working on my testing server.

This is what got to work in the end.

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

     }
   });
});

What i did find is though that nothing is returned from the script. EI any validation info or returned data? Not too much of a problem and i'll create a work around. Thank again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM