jQuery submit form without page reload

2019-02-28 13:31发布

Ok, so I'm trying to make a new log in form form my site using jquery and classic ASP. As of right now I have a containing div in my document thats set to hidden, then when the user selects the login link the div will fade in overlaying the page with the form. If the user clicks submit, the page will POST and the div overlay is gone. I would really like it to be more smooth than that. So if the users clicks submit, jquery will use ajax or something to post it in the background to a db connect page and then get the response text from that asp displaying either a successful login or incorrect in the errors label.

I use classic asp on my site to fetch the form data on submit with the previous login. then that checks the DB to see if what was entered matches.

I would like to have jQuery handle all this and send the values through a query or other method in the background to the ASP page containing the DB connection so the page doesn't reload when submit is clicked.

I've looked a a hand full of examples and I can't seem to get them going right.

Heres a FIDDLE to look at with the working functions so far.

Any help would be greatly appreciated, Thanks in advance.

<table cellspacing="0" cellpadding="0" width="900" >
      <tr>
            <a href="index.asp" class="linkheader">Home</a>&nbsp;&nbsp;|&nbsp;&nbsp;
            <a href="index1st.asp">1st</a>&nbsp;&nbsp;|&nbsp;&nbsp;
            <a href="index2nd.asp">2nd</a>&nbsp;&nbsp;|&nbsp;&nbsp;
            <a href="index3rd.asp">3rd</a>&nbsp;&nbsp;|&nbsp;&nbsp;
            <a href="index4th.asp">4th</a>&nbsp;&nbsp;|&nbsp;&nbsp;
            <a href='#' id='login' class='linkheader'>Log In</a></td>
     </tr>
</table>

<!-- blur_login is transparent overlay. starts as hidden untill link is selected -->
<div id="blur_login">
    <!-- show_login is container for login form -->
    <div id="show_login">

        <a class="OKclose" href="#" >[ Close ]</a>

        <form method="" id="getin">
        <p><label for="Username">Username</label><br />
        <input name="Username" id="users" type="text" size="14" maxlength="14" autocomplete="off" tabindex="1"/>
        </p>
        <p><label for="last_name">Password</label><br />
        <input name="last_name" type="password" size="14" maxlength="14" autocomplete="off" tabindex="2" /><br />
            <label for="errors"></label>
        </p>
    <p><input type="submit" id="send" value="Log In &rarr;"></p>
</form>
    </div>
</div>

$(document).ready(function() {
$(window).bind("resize", function(){
   $("#blur_login").css("height", $(window).height());
   $("#blur_logout").css("height", $(window).height());
});

//Adjust height of overlay to fill screen when page loads
   $("#blur_login").css("height", $(document).height());

    $('#login').click(function(a){
        $("#blur_login").fadeIn();
        // Page focus on fadein is the username input
        $('#users').focus(); 
        a.preventDefault;
        return false;
    });

    $('#logout').click(function(b){
        $("#blur_logout").fadeIn();
        b.preventDefault;
      return false;
    });

    $('#send').click(function(c){
        //AJAX form submit here
    });

// Functions for login form
var $submit = $("input[type=submit]"),
    $inputs = $('input[type=text], input[type=password]');

// Checks if fields are empty, if so then disable loginbutton
    function checkEmpty() {
        return $inputs.filter(function() {
            return !$.trim(this.value);
        }).length === 0;
    }
// Enables the submit button when characters have been entered in each field
    $inputs.on('keyup blur', function() {
        $submit.prop("disabled", !checkEmpty());
    }).keyup();  // trigger any one

// When the close link is selected the window will fade out
   $(".OKclose").click(function(d){
      $("#blur_login").fadeOut();
       d.preventDefault;
      return false;
});   
});​

4条回答
对你真心纯属浪费
2楼-- · 2019-02-28 14:07

To stop a form from reloading the page, this is what I use, it's been tested to work in all major browsers:

function doStuff(e){
    e.returnValue = e.preventDefault && e.preventDefault() ? false : false;
    // handle AJAX here
}

Of course, you'll need to add an onsubmit to the form to call doStuff(event);.

查看更多
虎瘦雄心在
3楼-- · 2019-02-28 14:13

Well you're certainly correct about the necessity to use (jQuery's) AJAX for this. Here's an example of what you should put in the form submit click handler.

$.ajax({
  type: "POST",
  url: "dbProcessing.asp",
  data: $('#loginForm').serialize(),
  success: function(){
  // Insert any changes into the DOM that you like
  // msg will be whatever you print out in dbProcessing.asp
  // so set it to 'success' or something if the login was successful
  // and then do an if statement to see what === msg and insert
  // a message into the DOM or redirect based on that
  }
});

Edited for better practice (as per comment)

Edit2: now I'm just getting careless

查看更多
smile是对你的礼貌
4楼-- · 2019-02-28 14:23

Try use jQuerys post method:

$.post("dbProcessing.asp", $("#loginForm").serialize(), function(data)
{
    // TODO: function logic
});

Here you can find the manual for jQuery.post()

查看更多
姐就是有狂的资本
5楼-- · 2019-02-28 14:24

Here is what I use in my pages:

$('#loginbutton').click(function(event) {
    event.preventDefault(); /*  Stops default form submit on click */       
        $('#loginbutton').hide();                                                               //Hide Login Button
        $('#loginprogress').html('<img src="web/imgs/loader.gif"> Processing'); // Show Progress Spinner

        var username = $("#username").val();
        var password = $("#password").val();

        $.ajax({                                                                                        // Run getUnlockedCall() and return values to form
            url: "ajaxDispatcher.php?action=login",
            data: 'username=' + username + '&password=' + password,
            type: "POST",
            success: function(data){
                if (data == '') {
                    $('#loginbutton').show();                                               // Show Login button
                    $('.error').show();                                                     // Display login error message
                    $('#loginprogress').html('');                                           // Show Progress Spinner
                } else {
                    location.reload();
                    $('#logout').show();                                                        // Show logout button
                            $('#userinfo').show();
                    $('#loginprogress').hide();                                         // Hide Progress Spinner
                }
            }
            });
        });

In a nutshell, #loginbutton is a jquery button. On click it hides to prevent multiple submissions. The dispatcher runs a function that checks the login, using the passed values from inputs with id "username" and "password". On success, if the login failed it will return false (showing an error warning), else it will return values to manipulate the dom. In this example, it shows the logout button, hides the loginprogress div, and shows a div called "userinfo".

查看更多
登录 后发表回答