0

I have the following signup form near the bottom of a new website. As soon as the AJAX response loads, the page skips to the top of the page. As far as I can tell, I have included "return false" correctly. What am I missing? Thank you!

## index.php ##

<script type="text/javascript" src="mailing-list.js"></script>
<div class="signup container">
  <form id="signup-form" action="<?=$_SERVER['PHP_SELF']; ?>" method="get">
    <fieldset>
      <legend><h2 style="align:center;">Enter Your Email Address</h2></legend>               
        <div class="row">
          <div class="offset4 span3">
            <input class="email" type="text" name="email"  id="email" />
          </div>
          <div class="span1">
            <input type="submit" name="submit" value="Join"  class="btn btn-large btn-primary" />
          </div>
        </div>
      <div id="response">
        <? require_once('inc/store-address.php'); if($_GET['submit']){ echo storeAddress();  } ?>
      </div>
    </fieldset>
  </form>
</div>

## and mailing-list.js ##

$(document).ready(function() {
  $('#signup-form').submit(function() {
    // update user interface
    $('#response').html('Adding email address');
    // Prepare query string and send AJAX request
    $.ajax({
      url: 'inc/store-address.php',
      data: 'ajax=true&email=' + escape($('#email').val()),
      success: function(msg) {
        $('#response').html(msg);
      }
    });
    return false;
  });
});
4

3 回答 3

3
$(document).ready(function() {
  $('#signup-form').submit(function(e) {
    e.preventDefault();
    // update user interface
    $('#response').html('Adding email address');
    // Prepare query string and send AJAX request
    $.ajax({
      url: 'inc/store-address.php',
      data: 'ajax=true&email=' + escape($('#email').val()),
      success: function(msg) {
        $('#response').html(msg);
      }
    });
    return false;
  });
});
于 2013-06-07T21:50:41.357 回答
1

I doubt it is executing the default form submit behavior. Prevent it byt using the preventDefault method.

$(function(){

   $('#signup-form').submit(function(e) {
     e.preventDefault();

     //your existing code goes here

   });

});
于 2013-06-07T21:49:29.783 回答
1

You need to prevent the form from submitting the data (even if it is to the same file). Otherwise the page will reload before your ajax call is done. You do this with .preventDefault();

Try

 ...
    $('#signup-form').submit(function(event) {
        event.preventDefault();
        // update user interface
     ...
于 2013-06-07T21:49:48.990 回答