简体   繁体   中英

My ajax script will run once correctly but it wont run again

So I seem to be having some issues with my code. Now I have just started learning AJAX and jquery so I am very new at it. They way the the site works is:

When a user clicks the Login button a form will appear under the button where they enter a username and password. When the user clicks login my ajax script will handle logging them in and refreshing their avatar so they know they are logged in. Then when they want to log out they click logout and it logs them out no problem.

The problem I am having is once I have run through the login/logout process I am unable to get the form to show up again without refreshing the page.

I hope I made sense =/ Here is the code I have:

<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/jscript"></script>
<script>
  $(function () {
    $('form').on('submit', function (e) {
      $.ajax({
        type: 'post',
        url: 'loginsystem/login.php',
        data: $('form').serialize(),
        success: function () {
            $("#loginForm").slideUp('slow');
            $("#playerFace").load('ajaxPHPScripts/getUserAvatar-100px.php');
            $("#loginLogout").load('ajaxPHPScripts/loginLogoutButton.php');
        }
      });
      e.preventDefault();
    });
  });
function doSomething() {
    $.ajax({
        type: 'get',
        url: 'loginsystem/logout.php',
        success: function () {
            $("#playerFace").load('ajaxPHPScripts/getUserAvatar-100px.php');
            $("#loginLogout").load('ajaxPHPScripts/loginLogoutButton.php');
        }
      });
}
$(document).ready(function(){
    $("#loginForm").hide();
  $("#loginbtn").click(function(){
    $("#loginForm").slideToggle('slow');
  });
});
$(document).ready(function() {
    $("#removeLoginForm").click(function(){
        $("#loginForm").slideUp('slow');
    });
});
</script>

Now for the html:

<div id="sidebar">
            <div id="sidebarinner">
                <div id="sidebarInnerInner">
                    <div id="playerAvatar">
                        <table width="100%" border="0" cellspacing="0" cellpadding="0">
                          <tr>
                            <td style="width:100px;" id="playerFace"><img src="https://minotar.net/avatar/steve/100"></td>
                            <td style="text-align:center;"><?php ServerPing(); //pings to see if server is online?></td>
                          </tr>
                        </table>
                    </div>
                    <div id="joinAndLog">
                        <table width="100%" border="0" cellspacing="0" cellpadding="0" style="text-align:center; height:100%;">
                            <tr>
                                <td style="width:50%;" id="loginLogout"><?php LoginOrLogout(); ?></td>
                                <td style="width:50%;"><?php SignupOrManageAcc(); ?></td>
                            </tr>
                        </table>
                    </div>

                    <div id="loginForm">
                        <form class="sideForm" id="testform" style="text-align:center;  margin-bottom:10px;"> 
                            <input type="text" id="name" name="username" value="" placeholder="Username..."/> 
                            <br />
                            <input type="password" id="pass" name="password" value="" placeholder="Password..."/> 
                            <br />
                            <input id="submit" type="submit" name="submit" value="Login" style="width:25%; cursor:pointer;" /> 
                            <input type="reset" name="" value="Cancle" id="removeLoginForm" style="width:25%; cursor:pointer;" />
                            <br />
                            <!--a href="#" style="padding:0px; margin:0px;">Forgot Password</a-->
                        </form> 
                     </div>
</div>

If you're loading content dynamically, then you need to either rebind the static event handlers to the object in the dynamically loaded content or you need to use delegated event handlers that will still work on the dynamically loaded content. The delegated event handlers are the more elegant solution.

A delegated event handler would look like this:

$('#sidebar').on('submit', '#loginForm', function() {...});

Ideally, you'd put an id (I suggested "loginForm" in my code example on the specific login form and use that instead of "form" for the target selector so you know the event handler targets only the correct form.

Using delegated event handling that is bound to a parent element that is not dynamically created/destroyed, but a select that targets the specific dynamic content inside that static parent allows you to keep the event handler in force even if the target content is destroyed and then reloaded.

You need to bind the newly loaded form the same way you did the first form.

So, after you load in the new HTML, you need to run something like this again:

$('form').on('submit', function (e) {
  $.ajax({
    ///// snip /////
  });
  e.preventDefault();
});

Since this inside function is repeated, you might as well define it outside.

Ie

var onFormSubmit = function (e) {
  $.ajax({
    ///// snip /////
  });
  e.preventDefault();
}

Now to bind the form to that function, you simply do:

$('form').on('submit', onFormSubmit);

Updated code:

$(document).ready(function(){
 $("#loginForm").hide();
 $("#loginbtn").on('click',function(){ // use .on() method
 $("#loginForm").slideToggle('slow');
});
});
$(document).ready(function() {
 $("#removeLoginForm").on('click',(function(){ // use .on() method
 $("#loginForm").slideUp('slow');
});
});

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